CSS In Depth

CSS In Depth

CSS3, or Cascading Style Sheets Level 3, is the latest evolution of the CSS specification, which is used to style and layout web pages. Building on its predecessors, CSS3 introduces a wide array of new features and capabilities that enable developers to create visually appealing and responsive websites with greater ease and flexibility.

  1. CSS units of measurement
    1. Absolute units
    2. Relative values
  2. Grids and flexbox
    1. Grid
    2. Flexbox
      1. Properties for flexbox container
      2. Properties for flexbox items (child)
  3. Grid template area
    1. Process
  4. Additional resources
  5. All selectors and their specificity
    1. Specificity hierarchy
  6. Inline styles
    1. IDs
    2. Classes, attributes, and pseudo-classes
    3. Elements and pseudo-elements
  7. Pseudo-elements
    1. Syntax
    2. ::first-letter
    3. ::selection
    4. ::marker
    5. ::before and ::after
  8. CSS Pseudo cheat sheet
    1. Simple selectors
    2. Variations of simple selectors
    3. Descendant selectors/combinators
    4. Attribute selectors
    5. Pseudo-element selectors
    6. Additional resources
  9. Text effects
  10. CSS keyframes
    1. from{} and to{} keywords and using percentages(%) syntax
    2. Animation Example
  11. Animation and effects
    1. Transform property
  12. Multiple transform over the same element
    1. Syntax
  13. Transition property
    1. Transition shorthand 
    2. Syntax
  14. Animations and @keyframes
    1. animation property:
    2. Syntax
  15. @keyframes
  16. Multiple animations
  17. Preprocessors: sass, scss, Stylus
    1. SASS and SCSS
      1. Syntax
    2. Stylus CSS
    3. Additional resources
  18. Debugging
    1. Resources

CSS units of measurement

Absolute units

Absolute units are constant across different devices and have a fixed size. They are useful for activities like printing a page. They are not so suitable when it comes to the wide variety of devices in use today that have different viewport sizes. Because of this, absolute units are used when the size of the web page is known and will remain constant.

Unit Name Comparison
Q Quarter-millimeters 1Q = 1/40th of 1cm
mm Millimeters 1mm = 1/10th of 1cm
cm Centimeters 1cm = 37.8px = 25.2/64in
in Inches 1in = 2.54cm = 96px
pc Picas 1pc = 1/6th of 1in
pt Points 1pt = 1/72nd of 1in
px Pixels 1px = 1/96th of 1in

Relative values

When you create a web page, you will almost never have only a single element present inside it. Even in case of containers such as flexboxes and grids, there’s usually more than one element present that rules are applied to. Relative values are defined ‘in relation’ to the other elements present inside the parent element. Additionally, they are defined ‘in relation’ to the viewport or the size of the visible web page. Given the dynamic nature of web pages today and the variable size of devices in use, relative units are the go-to option in many cases. Below is a list of some of the important relative units.

Unit Description and relativity
em Font size of the parent where present.
ex x-co-ordinate or height of the font element.
ch Width of the font character.
rem Font size of the root element.
lh Value computed for line height of parent element.
rlh Value computed for line height of root element which is <html>.
vw 1% of the viewport width.
vh 1% of the viewport height.
vmin 1% of the smaller dimension of viewport.
vmax 1% of the larger dimension of viewport.
% Denotes a percentage value in relation to its parent element.

Grids and flexbox

Grid

The syntax for creating a grid:

selector{
    display: grid; /* or inline-grid */
}
Properties Default values
grid A grid will allow you to organize the various elements on your page.
grid-template-rows: none This feature allows you configure your elements so that they are organized similarly to rows on a table.
grid-template-columns: none This feature allows you configure your elements but with this setting the elements are organized like columns on a table.
grid-template-areas: none This feature allows you configure the names of a grid and how they sit in relation to one another.
grid-auto-rows: auto Default setting for all row sizes that have not been explicitly configured.
grid-auto-columns: auto Default setting for all column sizes that have not been explicitly configured.
grid-auto-flow: row Default location for rows that are not explicitly allocated.
column-gap: normal This sets the gap between the columns
` row-gap: normal ` This sets the gap between the rows
Grid properties for container  
grid-template-columns: measurement units \| % units \|repeat() Defines the line names, and maintains a constant size of column items. Can accept a range of different measurement sizes.
grid-template-rows: measurement units \| % units \|repeat() Defines the line names, and maintains a constant size of rows. Can accept a range of different measurement sizes.
grid-auto-columns: measurement unit (fixed value for all columns) Determines the default size for columns that have not been explicitly configured.
grid-auto-rows: measurement unit (fixed value for all rows) Determines the default size for rows that have not been explicitly configured.
grid-template: “header header” auto This allows you define and maintain named cells on a grid
“main right” 75vh This defines two cells named main and right, that have a sizing of 75% of the viewport height.
“footer footer” 20rem This defines two cells named footer and footer, that have a sizing of 20 root em (rem). This defines the size in relation to the html font size.
Gap  
grid-gap: measurement units Determines the gap between rows and columns
grid-column-gap: measurement units Determines the gap between columns
grid-row-gap: m-unit-1 m-unit-2 Determines the gap between columns
Alignment  
justify-items: start \| center \| end \| stretch Defines the default space that is allot to each item on the grid
align-items: start \| center \| end \| stretch Defines the default space related to an item along the grid’s block axis
place-items: start \| stretch /* shorthand for two properties above */ This feature allows you align items with the block and inline directions.
Justification  
justify-content: start \| center \| end \| stretch \| space-between \| space-evenly \| space-around Defines browser allocation of space to content items in relation to the main-axis
align-content: start \| center \| end \| stretch \| space-between \| space-evenly \| space-around Defines browser allocation of space to content items in relation to cross axis and block axis
place-content: center \| start This feature allows you align items with the block and inline directions.
Positioning  
grid-auto-flow: row \| column \| dense This relates to how the items are placed automatically within the grid
grid-auto-columns: measurement units This relates to the size for columns created without specific size specifications
grid-auto-rows: measurement units This relates to the size for rows created without specific size specifications
Grid properties for items (child)  
grid-column: column position /* E.g. 1/2 */ Allows for specifying where on the grid the column is to start.
grid-column-start: column start position This property determines the starting column position an item is placed on a grid.
grid-column-end: column end position This property determines the end column position an item is placed on a grid.
grid-row: row position /* E.g. 1/2 */ Allows for specifying where on the grid the row is to start.
grid-row-start: row start position This property determines the starting row position an item is placed on a grid.
grid-row-end: row end position This property determines the end row position an item is placed on a grid.
Justification and alignment
justify-self: start \| center \| end \| stretch Determines how an item is positioned inside its aligned container in relation to the appropriate axis.
align-self: start \| center \| end \| stretch Aligns an item within a grid area.
place-self: start \| stretch /* shorthand for two properties above */ This setting lets one align and justify an item within a block.

Flexbox

The syntax for creating a flexbox:

selector{
	display: flex | inline-flex
}

Here the selector can refer to any of the following flex attributes

  • Attribute selector
  • Class Selector
  • ID Selector
  • Type Selectors
  • Universal Selectors

The display relates to how you want the selector to be shown. Setting display to flex makes the given selector a flex box. Setting display to inline-flex makes the selector a flex box container while will be inline.

Properties for flexbox container

flex-direction: row | row-reverse | column | column-reverse It is possible to specify the direction your elements will follow. Traditionally text goes from left to right which is flex’s default setting however it can be set from right to left or even top to bottom. The four flex-direction are:

  • row : organized from left to right
  • row-reverse: organized from right to left
  • column: organized from top to bottom
  • column-reverse: organized from bottom to top.

flex-wrap: wrap | nowrap The standard layout is to plot the elements from left to right in a straight line. The wrap feature allows you to customize this to match the size of the window displaying the page.

  • wrap: Automatically wrap the items with as the window space gets smaller.
  • nowrap: Default setting, items remain rigid and don’t respond to adjustments made to the window size.

align-items: flex-start | flex-end | center |Stretch This determines how the flex items are to be positioned on the page. Items can be aligned in a variety of ways

  • flex-start: Similar to standard writing, items start at the top left-hand corner and are positioned from left to right
  • flex-end: Position begins in the bottom right hand corner.
  • center: Item is positioned from the center.
  • stretch: item expands to fill the container.

justify-content: flex-start | flex-end | center | space-between | space-evenly Justify-content determines the alignment of the flex items.

  • flex-start: goes from right to left along the main axis.
  • flex-end: goes from left to right along the main axis.
  • center: Starting at the middle, alignments expands from there.
  • space-between: first and last item are flush with the left and right wall respectively, every other item is evenly spaced.
  • space-evenly: each item is equidistant from each other and the boundary wall

Properties for flexbox items (child)

Properties  
flex-grow: factor of flex’s main size This attribute enables the flex container to grow proportionally to the other containers present.
flex-shrink: factor of flex’s main size This allows elements to shrink in relation to items around it.
flex-basis: auto \| factor of main’s size \| measurement unit The sets the initial main size of an item. It can be overridden if other stylized elements are configured.
order:position in flex /* Set ascending by default */ The standard positioning of items is by source order, however this feature will enable you to configure where the items appear on the page.
align-self: start \| center \| end \| stretch This determines where on the page the child items will be positioned. Similar to the main flex attributes, start is to the left and end is to the right.

Grid template area

Grid areas are a way to group one or more grid cells. The grid template area is an extension of this concept where you can give names to these grid areas. Once you have the names defined, you can address these new grid area items by their names and configure them accordingly. 

The property grid-template-area is usually placed inside the body tag or any container where the grid needs to be placed, the same way that you would define the rules for the grid. The main difference is, in case of grid-template-area the values present will be the different names. 

Process

The process isn’t prescriptive but these are the steps in general:

  • Define the grid using display property 
  • Set the height and width of the grid 
  • Set the grid-template-areas with the appropriate name identifiers
  • Add the appropriate sizes for the rows inside the grid using grid-template-rows property 
  • Add the appropriate sizes for the columns inside the grid using grid-template-columns property 

But how exactly do you use these names and where do they come from? The names that you use inside the grid template areas are the HTML tags that you have used. Or, where you need to get more specific, you designate a class name to these tags. Once the names are assigned, you define the properties for each class the same way that you define them conventionally.

<!--file: "index.html"-->
<head>
<link rel="stylesheet" href="gridta.css">
</head>

<body>
	<header> Header </header>
	<nav class="nav-bar"> Navigation </nav>
	<main> Main area </main>
	<footer> Footer </footer>
</body>
/* file: "style.css*/
body {
	display: grid;
	height: 200px;
	grid-template-areas: "head head"
						 "nav main"
						 "footer footer";
	grid-template-rows: 30px 1fr 30px;
	grid-template-columns: 150px 1fr;
}
header {
	grid-area: head;
	background-color: lightsalmon;
}
.nav-bar {
	grid-area: nav;
	background-color: lightblue;
}
main {
	grid-area: main;
	background-color: lightyellow;
}
footer {
	grid-area: footer;
	background-color: firebrick;
}

Though there are five sets of rules, logically the CSS code is divided into two sections. The first is where you define the rules for the grid inside the body selector. And second is where you allocate specific rules for the different grid areas. The way these grid areas are distributed is according to how you have defined the names inside the grid-template-areas property. In the example above the relevant code is:

grid-template-areas: "head head"
					 "nav main"
					 "footer footer";

The ‘head’ is written twice to imply two columns and the rest of the content follows the usual convention. The number of rows will be the number of ‘pairs of quotes’ you have used which in this case is three. Namely “head head”, “nav main” and “footer footer”. Once you know the number of rows and columns, the values for those will be set by grid-template-rows and grid-template-columns. Since these are three and two respectively here, you need to add that many values. The height simply gives the overall value of the height for the grid.

Note that the number of times you wrote “header” did not have to be two. You could write more of those and if you align the rest of the grid-names correctly, the height and width of the grid-areas will be distributed proportionately.

Additional resources

Here is a list of resources about layouts, flexboxes, grids and viewports in HTML and CSS that may be helpful as you continue your learning journey.

Broad overview of layouts in CSS Detailed overview of flexboxes Detailed overview of grids (1) Detailed overview of grids (2) Viewports in CSS Grid layout applications Overview of different layouts

All selectors and their specificity

As you build a website, the complexity of the code might increase to such a point that more than one CSS rule is applied to the same element. Or, you might accidentally add more than one rule over the same element. This results in conflicts as only one rule can be applied to a specific property. For example, the color of a certain p tag can either be blue or white, but not both. CSS engines use something called specificity to resolve these conflicts. Specificity is the ranking or score that helps CSS determine the final rule that will be applied to a given element. 

This reading will help you grasp how the element with the ‘highest’ specificity is selected by CSS. But before you read on, it is important to note that these rules only apply in cases where conflicts arise for the properties. 

Specificity hierarchy

CSS has a set of rules that it uses to ‘score’ or assign a certain weight to selectors and this creates a specificity hierarchy. Based on the weights, there are four categories in this hierarchy: 

  • Inline styles 

  • IDs 

  • Classes, attributes, and pseudo-classes 

  • Elements and pseudo-elements 

Inline styles

Inline styles are attached to the elements within your HTML code like with the ‘style’ attribute. inline styles have the highest specificity. That means that rules that are defined as inline styles will be applied irrespective of other rules. 

IDs

Next in the hierarchy are IDs and by now you know that they are represented by ‘#’. 

Classes, attributes, and pseudo-classes

Classes, and the attributes inside the selectors, come next with what is called the pseudo-classes that you will soon learn more about. 

Elements and pseudo-elements

Finally, elements and something you call pseudo-elements have the lowest position in the specificity hierarchy. You will learn more about pseudo-elements later in this lesson.

Pseudo-elements

By now you know that pseudo-elements help you style a specific part of an element. For example, you can decide to apply styling to only the first word or line in a given element. First, let’s examine the syntax of a pseudo-element.

Syntax

selector::pseudo-element {
	 property: value;
}

It is important to note that pseudo-elements use two colon characters instead of one.

Now, let’s explore some examples of popular pseudo-elements.

::first-letter

You can use first-letter to change the color of just the first letter of each of the three points in the example text.

<!--file: "index.html"-->
<!DOCTYPE html>
<html>
	<head>
	<link rel="stylesheet" href="pseudo4.css">
	</head>
	<body>
		<ul>
			<li>Based in Chicago, Illinois, Little Lemon is a family-owned Mediterranean restaurant, focused on traditional recipes served with a modern twist. </li>
			<li>The chefs draw inspiration from Italian, Greek, and Turkish culture and have a menu of 12–15 items that they rotate seasonally. The restaurant has a rustic and relaxed atmosphere with moderate prices, making it a popular place for a meal any time of the day.</li>
			<li>Little Lemon is owned by two Italian brothers, Mario and Adrian, who moved to the United States to pursue their shared dream of owning a restaurant. To craft the menu, Mario relies on family recipes and his experience as a chef in Italy.</li>
		</ul>
	</body>
</html>
/* file: "style.css" */
li::first-letter {
	color:coral;
	font-size: 1.3em;
	font-weight: bold;
	line-height: 1;
}

Similar pseudo-element: ::first-line

::selection

Selection is another useful pseudo-element. For example, you may use it when you are taking notes on your device because it allows you to highlight specific text. The effect of it becomes obvious only after the user selects content.

ul{
	list-style-type: none;
}

li::selection {
	color:brown;
	background-color: antiquewhite;
	line-height: 1;
}

::marker

Markers are typically used to add style elements to a list, for instance, to color bullet points. For example, you can enhance the user experience when you use a marker in the following way.

li::marker {
	color: cornflowerblue;
	content: '<> ';
	font-size: 1.1em;
}

::before and ::after

One more pair of pseudo-elements are the ::before and ::after pseudo-elements. They allow you to add content before and after an element on which they are allowed. In other words, new content can be added to a page without adding HTML code for it. You can also add styling options for this content.

<!-- file: "index.html"-->
<body>
	<p id="tips"> Don't rinse your pasta after it is drained. </p>
	<p> Slice the tomatoes. Take the extra efforts to seed them. </p>
	<p id="tips"> Peel and seed large tomatoes. </p>
</body>
/* file: "style.css" */
#tips::before{
	background: darkkhaki;
	color:darkslategray;
	content: "Tip:";
	padding-left: 3px;
	padding-right: 5px;
	border-radius: 10%;
}

#tips::after{
	background:darkkhaki;
	color:darkslategray;
	content: "!!";
	padding-right: 5px;
	border-radius: 20%;
}

CSS Pseudo cheat sheet

Simple selectors

Selector Syntax Example
Element element div { }
Class .class .alpha { }
ID #id #alpha { }
Universal * * { }

Variations of simple selectors

Elements Syntax Example Description
Two classes .first-class.second-class .alpha.beta { } All elements with classes alpha and beta
Element and class element.class p.alpha { } All alpha class elements inside <p>
Two elements element, element p, div { } All <p> and <div> elements
Two elements element element p div { } All <div> elements inside <p>

Descendant selectors/combinators

Selector Syntax Example Description
Descendant element element div p { } All <p> descendants of <div>
Child element>element div > p { } All <p> direct descendants of <div>
Adjacent Sibling element+element div + p { } <p> element directly after <div>
General Sibling element~element div ~ p { } All <p> element iterations after <div>

Attribute selectors

Selector Syntax Example
[attribute] [href] {<br><br>} Selects all elements with a href attribute
[attribute=value] [lang="fr"] {<br><br>} Selects all elements with lang attribute that has a value of “fr
[attribute~=value] [input~=hello] {<br>} Elements with input attribute containing the whitespace separated substring “hello”
[attribute\|=value] [lang\|=en] {<br>} Elements with lang attribute value equal to “en” or “en-“(en hyphen)
[attribute^=value] a[href^="https"] {<br>} Every <a> element with href attribute value begins with “https
[attribute$=value] a[href$=".docx"] {<br>} Every <a> element with href attribute value ends with “.docx
[attribute*=value] a[href*="meta"] {<br>} Every <a> element with href attribute value has substring “meta
Pseudo-class Example Description of selection
:active a:active { } All active links
:checked input:checked { } All the checked <input> elements
:default input:default { } All default <input> elements
:disabled input:disabled { } All disabled <input> elements
:empty div:empty { } All the <div> elements with no children
:enabled input:enabled { } All the enabled <input> elements
:first-child p:first-child { } All the <p> elements who are the first child of a parent element
:first-of-type p:first-of-type { } All the <p> element who are the first <p> element of a parent element
:focus input:focus { } Input element under focus
:fullscreen :fullscreen { } The element in full-screen mode
:hover p:hover { } Action effect on mouse hover
:invalid input:invalid { } Input elements with an invalid value
:last-child p:last-child { } All the <p> elements who are the last child of a parent element
:last-of-type p:last-of-type { } All the <p> elements who are the last <p> element of a parent element
:link a:link { } All unvisited links
:not(_selector_) :not(div) { } All the elements that are not a <div> element
:nth-child(_n_) div:nth-child(3) { } All the <p> elements that are the third child of a parent element
:nth-last-child(_n_) div:nth-last-child(3) { } All the <div> elements which are the third child of a parent element, counting from last child element
:nth-last-of-type(_n_) p:nth-last-of-type(2) { } The second sibling from the last child of a parent element.
:nth-of-type(_n_) p:nth-of-type(2) { } The second sibling of a parent element.
:only-of-type p:only-of-type { } All the <p> elements which are only <p> elements inside its parent
:only-child p:only-child { } All the <p> elements which are only child of a parent element
:optional input:optional { } The input elements with no “required” attribute
:required input:required { } Selects input elements with the “required” attribute specified
:root :root { } The root element of document
::selection ::selection { } The portion of an element that is selected by a user
:valid input:valid { } All the input elements with a valid value
:visited a:visited { } Selects all visited links

Pseudo-element selectors

Syntax Example Description
::after p::after { } Inserts content after content of <p> element
::before p::before { } Inserts content before content of <p> element
::first-letter p::first-letter { } Selects first letter of every <p> element
::first-line p::first-line { } Selects first line of every <p> element
::placeholder input::placeholder { } Selects input elements with “placeholder” attribute specified
::marker ::marker { } Selects markers in a list

Additional resources

Here is a list of resources about selectors, pseudo-classes and pseudo-elements in HTML and CSS that may be helpful as you continue your learning journey.

Commonly used selectors Combinator selectors Comprehensive list of selectors Comprehensive list of pseudo-classes Comprehensive list of pseudo-elements

Text effects

The visual representation of text content can be changed by four main properties: text-transform, font-style, font-weight and text-decoration.

Property Values Description
text-transform none, uppercase, lowercase, capitalize, full-width Modify text properties
font-style normal, italic, oblique Font styling options such as italics
font-weight normal, weight, lighter, bolder, 100-900 Other font styling options like change of emphasis such as making text bold
text-decoration none, underline, overline, line-through Shorthand for auxiliary elements added to text using other properties such as text-decoration-line

The additional properties that help configure styling effects are below.

text-align For horizontal alignment of text
text-align-last Alignment for the last line when text set to justify
text-combine-upright Multiple characters into the space of a single character placed upright like in Mandarin
text-decoration-color Color configuration of the text-decoration
text-decoration-line Line type in text-decoration such as underline, overline and so on
text-decoration-style Styles added to lines under text such as wavy, dotted and so on
text-decoration-thickness Thickness of the decoration line
text-emphasis Shorthand for other properties such as color and style
text-indent The indentation of the first line
text-justify Specifies the justification method used when text-align is “justify”
text-orientation Orientation of text in a line such as sideways, upright and so on
text-shadow Adds shadow to text
text-underline-position Declare position of underline set using the text-decoration property

Other than these, there are some more properties that help modify the alignment and define the scope of text with their containers. 

Property Values Description
text-overflow clip, ellipsis Determines overflow behavior of text with the container
word-wrap normal, anywhere, break-word Applies to inline elements, alias for overflow-wrap
word-break normal, break-all, keep-all, break-word Used for long words to decide if words should break or overflow
writing-mode horizontal-tb, vertical-lr, vertical-rl Can set the text direction vertical or horizontal

CSS keyframes

Keyframes are a type of at-rule which are represented by the ‘@’ suffix. At-rules are statements inside CSS that describe how to behave or perform certain actions. In line with that, keyframes are defined as ‘@keyframes’ in the CSS code. @keyframes are part of the animation sequence and help in defining the steps inside it.

from{} and to{} keywords and using percentages(%) syntax

@keyframes animation-name {
	from {
		property-a: value-a;
	}
	to {
		property-a: value-b;
	}
}

The ‘from’ and ‘to’ keywords are used inside the @keyframes rule to mark the transition of one or more properties and can be seen as the start and end points of that transition. As can be seen from the syntax, the values of ‘property-a’ changes from ‘value-a’ to ‘value-b’. To expand on the use of ‘from’ and ‘to’, the @keyframes allows you to add more steps to your animation by using a percentage that represents the completion of the animation.

@keyframes identifier {
	0% {transform: rotate(100deg);}
	30% {opacity: 1;}
	50% {opacity: 0.50;}
	70% {opacity: 1;}
	100% {transform: rotate(50deg);}
}

The different percentages used in the example demonstrate the progression of the animation. Note that it doesn’t have to be the same property that you modify in these steps. That’s not possible using the transition property, but you can do it with @keyframes. This flexibility is what makes @keyframes so powerful. Another advantage is how these animations can also loop infinitely, run forwards, reverse and alternate.

@keyframes are tied in with the animation-name to which they are going to be applied. To give an overview of the animation property, it consists of other sub-properties. Of these, animation-name and animation-duration must be defined while others such as timing-function, delay, direction, fill-more, iteration-count and so on can be added.

Animation property shorthand: The shorthand for the animation property consists of the following properties with their default values:

  • animation-name: none 
  • animation-duration: 0s 
  • animation-timing-function: ease 
  • animation-delay: 0s 
  • animation-iteration-count: 1 
  • animation-direction: normal 
  • animation-fill-mode: none 
  • animation-play-state: running 
  • animation-timeline: auto
  • If the values of these are not defined, you should assume that they are the default. Of these, the first property of the animation-name is what’s used to tie it to the @keyframes rule.
<!-- file: "index.html"-->
<body>
	<div class="box"></div> 
</body>
/* file: "style.css" */
body {
	padding: 30px;
}
.box {
	background-color: lightcoral;
	width: 50px;
	height: 50px;
	animation: myanimation 3s infinite ease-in;
}
@keyframes myanimation {
	from {width: 50px;
	}
	to {width: 100px;
	}
}

If you modify this code and change the animation rules to percentages, it will have the same output.

@keyframes myanimation{
	0% {width: 50px;
}
	100% {width: 100px;
}

Animation Example

<!-- file: "index.html"-->
<!DOCTYPE html>
<html>
    <head>
        <title>Animation Example</title>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div id="ball"></div>
    </body>
</html>
/* file: "style.css"*/
@keyframes bounce {
	from {
	transform: translate3d(0, 0, 0)}
	to {
	transform: translate3d(640px, 0, 0)}
}

#ball {
	width: 80px;
	height: 80px;
	border-radius: 50%;
	background-color: #62687F;
    
    animation: bounce 2s;
    animation-direction: alternate;
    animation-iteration-count: infinite;
}

Animation and effects

Transform property

transform: transform function-values

.sample-class {
	transform: rotate(60deg);
}

Keyword-value type: none

.sample-class {
	transform: none;
}

Function-value type: matrix() Variations: matrix(), matrix3d()

.sample-class {
	transform: matrix(1.0, 2.0, 3.0, 4.0, 5.0, 6.0);
}

Function-value type: rotate(deg) Variations: rotate(), rotate3d(), rotateX(), rotate(), rotateZ()

.sample-class {
	transform: rotate3d(3,2,1, 100deg);
}

In rotate3d(), the respective values represent x, y, z co-ordinate and degree of rotations

Function-value type: translate(x,y) Variations: translate(), translate3d(), translateX(), translateY(), translateZ()

.sample-class {
	transform: translate3d(10px, 20px, 30px);
}

In translate3d(), the respective values represent translation along the x, y, z co-ordinates

Function-value type: scale(factor) Variations: scale(), scale3d(), scaleX(), scaleY(), scaleZ()

.sample-class {
	transform: scale3d(2, 1, 0.3);
}

In scale3d(), the respective values represent scaling times along the x, y, z co-ordinates

Function-value type: skew(deg, deg) Variations: skew(), skewX(), skewY()

.sample-class {
	transform: skew(100deg);
}

Global value types:

.sample-class {
	transform: inherit; /* initial, revert, revert-layer, unset  */
}

Multiple transform over the same element

Syntax

Transform can be applied for rotate(), scale() and translate() that can be listed together. Each of these properties can have their own values and the actions will give a combined effect.

.sample-class {
	transform: rotate(45deg) scale(1.5) translate(45px);
}

Additional property under transform:

transform-origin Determines the anchor point for the centering of transform.

.sample-class {
transform-origin: 10px 10px; /* also: right bottom; */
}

Transition property

Transition shorthand 

Transition shorthand has four following sub-properties, each of which can also be individually defined. 

  • transition-property
  • transition-duration
  • transition-timing-function
  • transition-delay

    Syntax

    transition: property duration timing-function delay;

	transition: margin-left2s ease-in-out 0.5s;

Animations and @keyframes

animation property:

Syntax

animation: name duration timing-function delay iteration-count direction fill-mode play-state;

.sample-class {
	animation: none 2 ease 0.5 4 normal none running;
}

The animation property is a shorthand for the sub-properties below:

	animation-name
	animation-duration
	animation-timing-function
	animation-delay
	animation-iteration-count
	animation-direction
	animation-fill-mode
	animation-play-state

The values not mentioned are given default values. animation-name property is used to tie-in the @keyframes rule.

@keyframes

@keyframes mymove {
  from {property: value}
  to { property: value }
}
@keyframes animation-name{
	from{bottom:0px;}
	to{bottom:100px;}
	}

Percentage denotes the timing of the animation.

@keyframes animation-name {
	0%,100%{
	background-color: blue;
	}
	50% {
	background-color: green;
	}
}

Multiple animations

Works the same as regular animation, multiple rules can be set.

#some-class{
	animation: animation-a 2s linear infinite alternate, 
	animation-b 3s ease infinite alternate;
}

Preprocessors: sass, scss, Stylus

CSS preprocessors are special compilers used to create a CSS file that can be referenced by an HTML document. They are generally used to reduce the amount of CSS you need to write and allow you to re-use values across multiple rules. This will make re-using animations and effects much easier. And because preprocessors are an extension of CSS they’ll help not just in animation but any CSS code.

Preprocessors provide audit functionality on top of the CSS features already present. Some of the features of preprocessors include the option to create variables, loops, and if else statements. Different preprocessors each have their own syntax and configurations for adding these features. Some of the most commonly used preprocessors include Sass, LESS, Stylus and PostCSS. The use of these preprocessors requires the installation of a compiler on top of your web server.

SASS and SCSS

This example highlights these differences.

body {
	font: 100% Arial;
	color: lightblue;
}
$font-stack: Arial;
$primary-color: lightblue;

body {
	font: 100% $font-stack;
	color: $primary-color;
}

SASS for the same block:

$font-stack: Arial
$primary-color: lightblue

body
	font: 100% $font-stack
	color: $primary-color

The variables have been defined at the top with labels such as ‘$font-stack’ and ‘$primary-color’. This is done with the ‘$’ suffix. The result for both will be the same, and it is not hard to imagine how much time this can save for the developer in complex code blocks where there are a number of occurrences of ‘lightblue’ color. These variables are placed at the top of the SCSS page.

In the case of SASS, the variation has mainly removed the curly brackets and semi-colons from the code. 

The nesting of selectors and separation of properties here is done by means of indentation. You should note that all this syntax is valid and will produce the same output.

Another important functionality in SASS is the use of directives. Let us explore a couple of directives called @mixin and @include. 

Syntax

@mixin name {
property: value; 
property: value; 
... 
}
@mixin some-rules {
	color: lightblue;
	font-size: 25px;
	font-weight: bold;
}
  
div {
	@include some-rules;
}

There are two directives @mixin and @include, that are used here. 

In the first step, you will add properties that you want to reuse inside @mixin

In the second step, you use the second directive @include and add the mixin identifier that you have created using the @mixin directive. 

Similar to these, there are a couple of other directives that are also used. @import allows the import of rules from another file, and @extend allows all the rules from a specific selector to be added inside another selector.

Stylus CSS

body
font 100% Arial
color lightblue

The preprocessors, as mentioned, allow the use of functions. Here is an example of this using Stylus.

add(a, b)
	a + b

div
	margin add(10px, 20px)

These functions are useful when adding color gradation or creating advanced geometric shapes on your web page.

Additional resources

Here is a list of resources about animation and keyframes in HTML and CSS that may be helpful as you continue your learning journey.

Transform and transition property Detailed information about animation Detailed information about @keyframes More advanced examples for adding text effects (1) More advanced examples for adding text effects (2) More advanced examples for adding text effects (3) Types of effects added to websites (1) Types of effects added to websites (2) Collection of examples using HTML/CSS

Debugging

Resources

The following resources will be helpful as additional references in dealing with the different concepts related to the topics you have covered in this lesson. 

Website to check for browser-compatibility Official website for Stylelint Widely used linter website to check CSS code CSS Validator to check accuracy of CSS code Dealing with specificity issues Beginner errors made in CSS Knowledge-based mistakes to avoid in CSS How to use Webkit in your CSS code Commonly-occurring browser issues in CSS


© 2024. knznsmn. All rights reserved.