CSS advanced

 

CSS Outline - Something Out of the Box Model


CSS Outline

CSS outline is a line that is drawn around the HTML element just outside of the border to make the element stand out.

The CSS outline looks just like the border, but it is drawn outside of the border. The outline is not part element's box model but the border is part of the element's box model.

CSS outlines are generally used to create focus on certain areas like buttons, forms, links, etc.

You can see the outline is around the element that lies outside the black border.

Example of CSS outline:

Example

.para {
    outline: 10px solid #5b79a2;
}
CSS
▶ Try it

# Syntax

/* Just type or style */
outline: type; /* (solid | dotted ...) */

/* width & type */
outline: width type;

/* color and type */
outline: width color;

/* width, color and style */
outline: width color style;
CSS

The order of the properties is not important. You can use any of the three properties in any order.

The other 2 properties width and color are optional but you have to mention the type or style of the outline every time you use them.

Example

.para1 { outline: solid }

.para2 { outline: 6px double}

.para3 { outline: dotted red }

.para4 { outline: dashed 4px #00f }

.para5 { outline: 4px dashed #00f }
CSS
▶ Try it
CSS outline example
Change the values from options to see the effect.

CSS Outline Property

The CSS outline has the following properties:

  1. outline-style
  2. outline-color
  3. outline-width
  4. outline-offset
  5. outline (shorthand)

1. CSS Outline Style

The outline-style property sets the style of an element's outline. The default outline-style is none.

The outline-style can have one following values:

  • solid - It defines a solid outline.
  • dashed - It defines a dashed outline.
  • dotted - It defines a dotted outline.
  • double - It defines a double outline.
  • groove - It defines a 3D grooved outline.
  • inset - It defines a 3D inset outline.
  • outset - It defines the 3D outset outline.
  • ridged - It defines a 3D ridged outline.
  • none - It defines no outline.
CSS outline style

Example

p.solid { outline-style: solid; }
p.dashed { outline-style: dashed; }
p.dotted { outline-style: dotted; }
p.double { outline-style: double; }
p.groove { outline-style: groove; }
p.inset { outline-style: inset; }
p.outset { outline-style: outset; }
p.ridge { outline-style: ridge; }
p.none { outline-style: none; }
CSS
▶ Try it
CSS outline-style example
Change the values from options to see the effect.

2. CSS Outline Color

The outline-color property sets the color to outline. The color can be set by any method like color name, HEX value, RGB value, HSL value, etc.

The default color of the outline is the same as the text color.

Example

.color1{
  outline-style: solid;
  outline-color: red;
}
.color2{
  outline-style: solid;
  outline-color: rgb(127, 65, 243);
}
.color3{
  outline-style: solid;
  outline-color: #23d43c;
}
CSS
▶ Try it
CSS outline-color example
Change the values from options to see the effect.

3. CSS Outline width

The outline-width property sets the thickness of the element's outline. outline-width has the following values:

  • thin - It defines an outline of generally 1px.
  • medium - It defines an outline of generally 3px.
  • thick - It defines an outline of generally 5px.
  • Any width - It defines an outline in px, pt, cm, etc.

Example

.thin {
  outline-width: thin;
}

.medium {
  outline-width: medium;
}

.thick {
  outline-width: thick;
}

.fivepx {
  outline-width: 5px;
}
CSS
▶ Try it
CSS outline-width example
Change the values from options to see the effect.

4. CSS Outline offset

The outline-offset property sets a gap between the border and outline. outline-offset value can be given in any valid unit. The default outline-offset value is 0.

Example

.offset-px {
  outline-offset: 5px;
}
.offset-rem{
  outline-offset: 1rem;
}
.offset-cm{
  outline-offset: 1cm;
}
CSS
▶ Try it
CSS outline-offset example
Change the values from options to see the effect.

5. CSS Outline shorthand property

The outline is a shorthand property for all CSS outline properties, which is used to set multiple outline property values in a single line.

Using outline property we can specify one, two, or all three values of outline property, where outline-style is the required property, outline-width and outline-color are optional properties. The order of these three doesn't matter.

Example

.order1 {
  outline: solid;
}

.order2 {
  outline: solid red;
}

.order3 {
  outline: solid 10px;
}

.order4 {
  outline: solid 10px red;
}
CSS
▶ Try it
CSS outline example
Change the values from options to see the effect.

Difference Between Border And Outline

The outline looks very similar to the border both are different from each other.

The difference between outline and border are as follows:

CSS outlineCSS border
The outline doesn't take up space and can overlap with other elements nearbyBorders do take space and do not overlap with another element
Outline do not change shape and size of elementBorder change the shape and size of the element
Outline can't be given different values to its different edges, it's the same in all directionsBorders can be given different values to the different sides of the border
Outline can't have another shape than a rectangleBorders can have any shape between square and circle
The outline does not have an impact on surrounding elementsBorders have an impact on surrounding elements
CSS outline vs border example
Change the values from options to see the effect.

CSS Text Outline

The text outline is a technique to draw a line around the text. It can be used to indicate some special text or to highlight some text.

The text-stroke property sets the outline of the text. It can be used to highlight text or to indicate some special text.

The property that sets text outline is under experiment and is only supported by the browsers that extend support to 'webKit'. So the syntax also uses the prefix of WebKit. The property is -webkit-text-stroke.

# Syntax

-webkit-text-stroke: color width;
/* or */
-webkit-text-stroke: width color;
CSS

Example

.para1 {
  -webkit-text-stroke: 2px #f00;
}

.para2 {
  -webkit-text-stroke: #f00 2px;
}
CSS
▶ Try it
CSS text-stroke example
Change the values from options to see the effect.

Conclusion

If you want to give an HTML element an effect of the border without changing the shape of the element, then use the outline property. The outline is not the part of element's box-model hence it does not even interact with surrounding elements.

To give an outline to texts you can use -webkit-text-stroke property.


Frequently Asked Questions

  1. What is outline?

    The outline is a rectangular line that is drawn around an element outside the border. It does not change the shape of the element.

  2. How do I make an outline in CSS?

    To make an outline in CSS, you can use the outline property. The syntax is outline: style width color.

  3. What is the use of outline in CSS?

    The outline is used to give an effect of the border without changing the shape of the element.

  4. What is CSS outline-color?

    The outline-color property sets the color of an outline.

Overflow in CSS


On a web page, we can have a lot of content. Sometimes, the content may be more than the size of the container. In such cases, the content will overflow the container.

The content that overflows the container is hidden by default. We can change this behavior using the overflow property.

CSS overflow example
Change the values from options to see the effect. Example text. Example text. Example text. Example text. Example text. Example text. Example text. Example text. Example text. Example text. Example text. Example text. Example text. Example text. Example text. Example text. Example text. Example text. Example text.

CSS overflow values

ValueDescription
visibleDefault value. Content is not clipped, it may be rendered outside the element's box.
hiddenContent is clipped and no scrollbars are provided.
scrollContent is clipped and scrollbars are provided.
autoIt also provides a scroll bar like the above property but in this scroll bar is provided only when it's necessary.

1. Overflow visible

By default, the overflow property is set to visible. This means that the content is not clipped, it may be rendered outside the element's box.

Example

.visible {
    overflow: visible;
}
CSS
▶ Try it

Output:

The content overflow and the content is visible outside the box.Lorem ipsum dolor sit amet consectetur adipisicing elit. Itaque consequatur mollitia enim quia et Itaque consequatur mollitia incidunt esse nihil dolore excepturi iste, nostrum amet quaerat cupiditate nisi dolor, exercitationem numquam!




Overflow hidden

When the overflow property is set to hidden, the content is clipped and no scrollbars are provided.

Example

.hidden{
    overflow: hidden;
}
CSS
▶ Try it

Output:


Overflow scroll

The overflow scroll value clips the content but extra content is visible by a scroll bar that is generated.

The scroll bar can be horizontal or vertical.

Example

.scroll {
    overflow: scroll;
}
CSS
▶ Try it

Output:

The content overflows and the content which is outside the box can be seen by scrolling.Lorem ipsum dolor sit amet consectetur adipisicing elit. Itaque consequatur mollitia enim quia et incidunt esse nihil dolore excepturi iste, nostrum amet quaerat cupiditate nisi dolor, exercitationem numquam!

Overflow auto

If the overflow is clipped then auto value creates a scroll to make overflowed content visible.

The scroll bar created by auto can be horizontal or vertical.

Example

.auto{
    overflow: auto;
}
CSS
▶ Try it

Output:

The content overflows and the content which is outside the box can be seen by scroll created by auto value.Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero, eligendi fugiat. Labore facereprovident dicta voluptatibus ea obcaecati quas asperiores hic, rem praesentium adipisci aliquid nisi. Rerum reprehenderit dolores laborum.

Overflow x and y

The overflow-x and overflow-y properties let us control the overflow of content in the x and y directions separately.

To control the overflow of content in the x direction, we use the overflow-x property.

To control the overflow of content in the y direction, we use the overflow-y property.

Example

.x {
    overflow-x: hidden;
}

.y {
    overflow-y: scroll;
}
CSS
▶ Try it

Different Types of Cursors in CSS


CSS cursor property is used to change the cursor type when the mouse pointer is over an element. Cursors are used to specify possible actions that can be performed on an element.

For example when you hover over a link, the cursor changes to a hand. This is because the cursor property is set to pointer.

Default property:auto
Version:CSS 2,3
Animation:no
Applies to:all element
Inherited:Yes

Different Types of Cursor Values

There are many different types of cursor values. Take your mouse pointer over these buttons and see how the pointer changes.

Following table shows the cursor property values and their corresponding cursors.

ValueCursor (hover your mouse on buttons below)
autoauto
defaultdefault
nonenone
initialinitial
inheritinherit
context-menucontext-menu
helphelp
pointerpointer
progressProgress
waitwait
cellcell
crosshaircrosshair
texttext
vertical-textvertical-text
aliasalias
copycopy
movemove
no-dropno-drop
not-allowednot-allowed
all-scrollall-scroll
col-resizecol-resize
row-resizerow-resize
n-resizen-resize
e-resizee-resize
s-resizes-resize
w-resizew-resize
ne-resizene-resize
nw-resizenw-resize
se-resizese-resize
sw-resizesw-resize
ew-resizeew-resize
ns-resizens-resize
nesw-resizenesw-resize
nwse-resizenwse-resize
zoom-inzoom-in
zoom-outzoom-out
grabgrab
grabbinggrabbing


Here is an example:

Example

<span style=cursor:auto;>auto</span>
<span style=cursor:default;>default</span>
<span style=cursor:none;>none</span>
<span style=cursor:initial;>initial</span>
<span style=cursor:inherit;>inherit</span>
<span style=cursor:context-menu;>context-menu</span>
<span style=cursor:help;>help</span>
<span style=cursor:pointer;>pointer</span>
<span style=cursor:progress;>progress</span>
<span style=cursor:wait;>wait</span>
<span style=cursor:cell;>cell</span>
<span style=cursor:crosshair;>crosshair</span>
<span style=cursor:text;>text</span>
<span style=cursor:vertical-text;>vertical-text</span>
<span style=cursor:alias;>alias</span>
<span style=cursor:copy;>copy</span>
<span style=cursor:move;>move</span>
<span style=cursor:no-drop;>no-drop</span>
<span style=cursor:not-allowed;>not-allowed</span>
<span style=cursor:all-scroll;>all-scroll</span>
<span style=cursor:col-resize;>col-resize</span>
<span style=cursor:row-resize;>row-resize</span>
<span style=cursor:n-resize;>n-resize</span>
<span style=cursor:e-resize;>e-resize</span>
<span style=cursor:s-resize;>s-resize</span>
<span style=cursor:w-resize;>w-resize</span>
<span style=cursor:ne-resize;>ne-resize</span>
<span style=cursor:nw-resize;>nw-resize</span>
<span style=cursor:se-resize;>se-resize</span>
<span style=cursor:se-resize;>sw-resize</span>
<span style=cursor:ew-resize;>ew-resize</span>
<span style=cursor:ns-resize;>ns-resize</span>
<span style=cursor:nesw-resize;>nesw-resize</span>
<span style=cursor:nwse-resize;>nwse-resize</span>
<span style=cursor:zoom-in;>zoom-in</span>
<span style=cursor:zoom-out;>zoom-out</span>
<span style=cursor:grab;>grab</span>
<span style=cursor:grabbing;>grabbing</span>
HTML
▶ Try it

Position in CSS


Position property in CSS is used to specify the type of positioning method used for an element.

Type of positioning means how the element is positioned in the document flow. Suppose we have a div element and we want to position it at the bottom right corner of the page or we want to show it on the top of the page. We can do this by using position property.


Types of Positioning

There are five different types of positioning methods for elements:

  1. static - Default value. Elements render in order, as they appear in the document flow.
  2. relative - Relative positioning moves an element in relation to its normal position.
  3. absolute - Absolute positioning positions the element relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed).
  4. fixed - Fixed positioning is a type of absolute positioning that positions the element relative to the viewport, which means it always stays in the same place even if the page is scrolled.
  5. sticky - Sticky positioning is a hybrid of relative and fixed positioning. The element is treated as relative positioned until it crosses a specified threshold, at which point it is treated as fixed positioned.
CSS position example
Left element
Target Element
Right element

Other content

Other content

Other content

Other content

Other content

Other content


1. Position static

Static positioning is the default value of the position property. Static positioning means that the element is not positioned in any special way; it is always positioned according to the normal flow of the page.

Static positioning is not a real positioning method. It is just the default value of the position property. Static positioning is used to remove the effect of any previous positioning method.

The element positioned static is not affected by topbottomleft, and right properties.

Example

.static {
  position: static;
  border: 3px solid #73AD21;
}
CSS
▶ Try it

2. Position relative

Position relative value sets the element relative to its normal value.

The position relative is followed by offsets either topbottomleft, or right. These offsets are used to move the element from its normal position.

Example

.relative {
  position: relative;
  left: 30px;
  top: 30px;
  border: 3px solid #73AD21;
}
CSS
▶ Try it

3. Position fixed

Position fixed value is used to set an element fixed to the page at any spot. Regardless of the page scroll, it doesn't move the element is fixed to its position.

The topbottomleft or right property is used to set the element where it should be located.

Example

.fixed {
  position: fixed;
  bottom: 0;
  right: 0;
  width: 300px;
  background-color: gold;
}
CSS
▶ Try it

4. Position absolute

The position absolute value is used to set the positioning of the element according to the nearest positioned parent. In case none of its parents is positioned then the element will position itself according to the document body.

The topbottomleft or right property is used to set the element where it should be located.

Note - The parent is called positioned only when it has any position value other than static.

Example

.parent{
    position: relative;
    top: 50px;
    left: 40px;
    background-color: gold;
}

.child{
    position: absolute;
    top: 10px;
    background-color: red;
}
CSS
▶ Try it

5. Position sticky

Position sticky value is used to make an element fix or stick at any location. Beyond that location, the element is free to move or scroll.

Position sticky value toggle between relative and fixed. This property is generally used to stick any element or note at the top of a web page.

Note - This property needs at least one value among the top, bottom, left, and right.

Example

.sticky {
    position: sticky;
    top: 20px;
    background-color: gold;
}
CSS
▶ Try it

Learn the difference between relative and absolute positioning in CSS.

CSS Display Property


CSS display property defines how an HTML element is displayed on the webpage.

If it is displayed as a block then it takes the full width of the webpage. If it is displayed as inline then it takes space equal to the width of the content.

Look at the image below to understand.

Difference in block and inline display
Difference in block and inline display

The CSS display property is used to specify the type of box used for an element.

Defining a display type not only affects the element itself but also its child elements.

Apart from the block and inline, there are many other values of the display property. We will see them below.


CSS Display Property Values

There are mainly 6 values of CSS display property.

  1. block - The element is displayed as a block element. It starts on a new line and takes up the whole width.
  2. inline - The element is displayed as an inline element. It does not start on a new line. It only takes up as much width as necessary.
  3. inline-block - The element is displayed as an inline-level block container. The element itself is formatted as an inline element, but you can apply height and width values.
  4. none - The element is completely removed. It will not be displayed, and it will not take up any space.
  5. flex - The element is displayed as a block-level flex container.
  6. grid - The element is displayed as a block-level grid container.
CSS display property example
Change the display value and see how 
testing text 12
 behaves. (justify-content value is space-between for testing purposes)

Let's look at these values in detail.


1. Display block

The block value displays the elements as a block. It breaks the line at the start and end of the element and covers the whole width of the container.

The elements having block as a default value are:

  • div - division tag
  • h1 - heading tag
  • p - paragraph tag
  • ul - unordered list tag

Example

.block {
    display:block;
}
CSS
▶ Try it


2. Display inline

The inline value displays the element within the line. It does not change lines or take any extra space.

When an element is displayed as inline, it takes only the width of the content. It does not support height and width properties.

Every HTML element has some default display value. Here are the elements that have inline as a default value:

  • a - anchor tag
  • b - bold tag
  • i - italic tag
  • span - span tag

Example

.inline {
    display:inline;
}
CSS
▶ Try it

3. Display inline-block

The inline-block value displays the element as an inline element, but you can apply height and width values.

It does not break the line and takes only width of the content. But it supports height and width properties.

The elements having inline-block as a default value are :

  • img - image tag
  • input - input tag
  • button - button tag

Example

.inline-block {
    display: inline-block;
}
CSS
▶ Try it

4. Display none

The none value removes the element from the document flow. It will not be displayed, and it will not take up any space.

Example

.hide {
    display: none;
}
CSS
▶ Try it

5. Display flex

The flex value displays the element as a block-level flex container. It is used to create flexbox layouts.

Flexbox is a layout mode in CSS3. It is a one-dimensional layout mode. It can arrange the elements in a row or column, but not both.

Example

.flex {
    display: flex;
}
CSS
▶ Try it


Conclusion

Understanding the display property is very important for a web developer. It helps us to create a better layout for our web pages.

Practice the examples given in this tutorial to understand the display property better.

CSS Shadow Effect


CSS Shadow is used to add a shadow effect to the HTML elements.

There are two types of shadows in CSS:

  • Box Shadow
  • Text Shadow

1. CSS box shadow

The box-shadow property is used to create shadow for the HTML elements.

The box-shadow creates a shadow around the element outside the element's border.

Syntax:

box-shadow: h-shadow v-shadow blur spread color inset;
CSS

Here is the explanation of the values:

ValueDescription
h-shadowRequired. The horizontal shadow position. Negative values are allowed.
v-shadowRequired. The vertical shadow position. Negative values are allowed.
blurOptional. The blur distance. Negative values are not allowed.
spreadOptional. The shadow size. Negative values are not allowed.
colorOptional. The shadow color. The default is black.
insetOptional. The shadow is inside the border.
CSS box-shadow example
Change the values from options to see the effect.

Let's see some examples:

Example

.simple {
  /* only horizontal and vertical value of shadow */
  box-shadow: 5px 5px;
}

.blur {
  /* blur value 5px */
  box-shadow: 5px 5px 5px;
}

.spread {
  /* spread value 5px */
  box-shadow: 5px 5px 5px 5px;
}

.color {
  /* color value red */
  box-shadow: 5px 5px 5px 5px red;
}

.inset {
  /* inset shadow */
  box-shadow: 5px 5px 5px 5px red inset;
}
CSS
▶ Try it


1.1 Multiple box shadow

You can add multiple box shadows to an element by separating the values with a comma.

There is no limit to the number of box shadows you can add to an element.

Just by using box-shadow correctly, you can create some amazing effects.

CSS multiple box-shadow example
Change the values from options to see the effect.

Let's see some examples:

Example

.multiple {
  /* multiple box shadow */
  box-shadow: 5px 5px, 10px 10px red;
}
CSS
▶ Try it

2. CSS text shadow

The text-shadow property is used to add a shadow effect to the text.

Using text-shadow property you can add horizontal or vertical shadow with different color and blur radius.

It is similar to box-shadow property but it is used to add shadow to text.

Syntax

The syntax of text-shadow property is given below:

text-shadow: horizontal vertical blur color;
CSS

Here, horizontal and vertical are the horizontal and vertical offset of the shadow and blur is the blur radius of the shadow.

CSS text-shadow example
Change the values from options to see the effect.

i. Simple text shadow

Example

p {
    text-shadow: 2px 2px;
}
CSS
▶ Try it

Output:

This paragraph has shadow property.


ii. Text shadow with different color

Example

p {
    text-shadow: 2px 2px red;
}
CSS
▶ Try it

Output:

This paragraph has blue shadow.


iii. Text shadow with different color and blur-radius

Example

p {
    text-shadow: 2px 2px 5px blue;
}
CSS
▶ Try it

Output:

This paragraph has blue shadow with blur-radius 5px.


iv. Multiple shadow

Example

p {
    text-shadow: 2px 2px 5px blue,
                 4px 4px 5px red,
                 -4px -4px 3px #006699;
}
CSS
▶ Try it

Output:

This paragraph has multiple shadow.

CSS Float Property


The CSS float property is used to place an element on the left or right side of its container, and allow text and inline elements to wrap around it.

Once an element is floated, it is removed from the normal flow of the page, and other elements will flow around it.

It is used to push HTML elements or containers left or right or to create a text wrapping effect around an image.


Float Property Values

You can set the float property to one of the following values:

ValueDescription
leftFloats the element to the left side of its container.
rightFloats the element to the right side of its container.
noneDefault value. The element does not float.
inheritSpecifies that the value of the float property should be inherited from the parent element.
inline-startFloats the element to the left side of its container in left-to-right text, or to the right side in right-to-left text.
inline-endFloats the element to the right side of its container in left-to-right text, or to the left side in right-to-left text.
CSS float property example
Floating Element
Change the float property from the options above and see the result.

CSS float left

The float property with the value left is used to float an element to the left side of its container.

The element having property float: left is pushed left to the container or to the nearest floated element.

Example

.box-left {
    float: left;
}
CSS
▶ Try it

CSS float right

The element having property float:right; is pushed right to the container or to the nearest floated element.

Example

.box-right {
    float: right;
}
CSS
▶ Try it

Note: The default value of the float property is none to keep the element in the normal flow of the page.

CSS clear property

The clear property is used to specify whether an element can be next to floating elements that precede it or must be moved down (cleared) below them.

It is used to control the element which will float beside the floating element.

If we specify value clear: left then no floating element will be allowed to the left side of the element.

If we specify value clear: right then no floating element will be allowed to the right side of the element.

Example

.float-left{
    float: left;
    border: 1px solid brown;
}
.clear{
    clear: left;
    border: 1px solid silver;
}
CSS
▶ Try it

CSS Text Align


CSS provides a property called text-align which is used to align the text in a block element. It can be used to align the text on the left, right, center, or justify.

The text-align has the following values:

  • left - It aligns the text to the left of the container. It is the default value.
  • right - It aligns the text to the right of the container.
  • center - It aligns the text to the center of the container.
  • justify - When the text-align property is set to justify, the text is aligned to both the left and right margins. The text is stretched to fill the entire line.
  • start - It aligns the text from the start of the container. When the direction: rtl then starting position is right so it will start from the right side and will look as if it's right aligned.
  • end - It aligns the text from the ending of the container. When the direction: rtl then the ending position is left so it will end at the left side and will look as if it's left aligned.
  • inherit - It inherits the text-align value from its parent element.
CSS text-align example
This is an example text. (Resize editor to see justify)

Let's see the example of the text-align property.


Example of text-align

We have a div element and inside it we have a p element. Let's test the text-align property on it.


text-align: left

By default, the text-align property is set to left. So, the text will be aligned to the left of the container.

Example

p {
  text-align: left;
}
CSS
▶ Try it

Output:

The text is aligned to the left of the container.


text-align: right

When the text-align property is set to right, the text is aligned to the right of the container.

Example

p {
  text-align: right;
}
CSS
▶ Try it

Output:

The text is aligned to the right of the container.


text-align: center

When the text-align property is set to center, the text is aligned to the center of the container.

Example

p {
  text-align: center;
}
CSS
▶ Try it

Output:

The text is aligned to the center of the container.


text-align: justify

The text is stretched to fill the entire line. When the text-align property is set to justify, the text is aligned to both the left and right margins.

Example

p {
  text-align: justify;
}
CSS
▶ Try it

Output:

The text is stretched to fill the entire line.


text-align: start

When the text-align property is set to start, the text is aligned from the start of the container. When the direction: rtl then starting position is right so it will start from the right side.

Example

p {
  text-align: start;
}
CSS
▶ Try it

Output:

The text is aligned from the start (left-to-right).

The text is aligned from the start (right-to-left).


text-align: end

When the text-align property is set to end, the text is aligned from the ending of the container. When the direction: rtl then the ending position is left so it will end on the left side.

Example

p {
  text-align: end;
}
CSS
▶ Try it

Output:

The text is aligned from the ending (left-to-right).

The text is aligned from the ending (right-to-left).


Also, learn how to center div elements and how to center images.

Using icons with CSS


Icons are used to add visual representation to the text. They are used to make the text more attractive and appealing. Icons are used in many websites to make the website more attractive and user-friendly.

The icon is a comprehensible symbol that is used to display something in the form of a sign or symbol on the computer screen.

Icons are available in many formats like SVG, PNG, JPG, etc. In this section, we will learn how to use icons in our website using CSS.

Here are some examples of icons:

Home
User
Mail
Phone
Search
Cart
Heart
Star

How to add icons

To add icons to the webpage you need to use the icon library.

These icon libraries create icons using CSS so that users can add other CSS properties to it too like color, shadow, size, etc.

These icons are embedded in webpage by using HTML tags like <i> or <span> tag with class attribute.

Here are some examples of icon libraries that you can use:

  1. Font Awesome
  2. Google Icons
  3. Bootstrap Icons

1. Font awesome icons

Font Awesome is a free icon library that is used to add icons to the website. It is a very popular icon library that is used by many developers.

To use font-awesome icons you first need to add the font-awesome library to your website using CDN.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css">
HTML

Note: You can also download the font-awesome library and add it to your website.

Every icon in the font-awesome library has a unique class name which is used to add that icon to the webpage.

For example, to add the home icon to the webpage you need to use the fa-home class.

You need to check the icon library to know the class name of the icon you want to add.

Example

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css">
  <title>CSS icon - Font Awesome</title>
</head>

<body>
  <h1>Created icons using font awesome library.</h1>
  <p><i class="fa fa-book"></i> - BOOK</p>
  <p><i class="fa fa-anchor"></i> - ANCHOR</p>
  <p>you can add class like - fa-2x,fa-3x to increase the size of icon.</p>
  <p><i class="fa fa-search fa-2x"></i> - SEARCH (2x)</p>
  <p>You can add color to icons using CSS.</p>
  <p><i class="fa fa-heart" style="color:red"></i> - HEART</p>
</body>

</html>
HTML
▶ Try it


2. Google icons

To use google icons you first need to add the google icons library to your website using CDN.

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
HTML

Visit the google icons website and click on the icon you want to add to the webpage. You will see the HTML code that you need to add to the webpage to add that icon.

Example

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
  <title>Material Icons</title>
</head>

<body>
  <h2>Created icons using Google font icons library.</h2>
  <div style="text-align:center">
    <i class="material-icons">home</i>
    <i class="material-icons">attachment</i>
    <i class="material-icons" style="font-size:2.5em">search</i>
    <i class="material-icons" style="color:red">favorite</i>
    <i class="material-icons" style="color:cyan">computer</i>
  </div>
</body>

</html>
HTML
▶ Try it

3. Bootstrap icons

To use bootstrap icons you first need to add the bootstrap icons library to your website using CDN.

Then use the appropriate class name to add the icon to the webpage.

Here is an example of how to add bootstrap icons to the webpage.

Example

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <title>Bootstrap</title>
</head>

<body>
  <h1>Created icons using Bootstrap icons library.</h1>
  <div style="text-align:center">
    <i class="glyphicon glyphicon-home" style="color:blue;font-size:1.5em"></i>
    <i class="glyphicon glyphicon-user" style="font-size:2em"></i>
    <i class="glyphicon glyphicon-remove" style="font-size:2.5em"></i>
    <i class="glyphicon glyphicon-envelope" style="color:red;font-size:3em"></i>
    <i class="glyphicon glyphicon-cloud" style="color:lightblue;font-size:3.5em"></i>
  </div>
</body>

</html>
HTML
▶ Try it

Styling Buttons in CSS


Buttons are the most important element of any website. They are used to perform an action. Buttons are used to submit a form, to open a modal, to open a link, to perform a function, etc. Buttons are used in almost every website. So, it is important to style them properly.

To create buttons we use the <button> tag. Sometimes we also use the <a> tag is used to create buttons for hyperlinks.

Let's look at 10 different types of buttons that we can create using CSS. But first, we will learn to add basic styling to buttons.


Basic Styles for Buttons

Let's look at some basic styles that we can apply to buttons.

  1. border - Sets the border of the button.
  2. padding - It helps to give the correct size to the button.
  3. background-color - Sets the background color of the button.
  4. color - Sets the color of the text inside the button.
  5. box-shadow - It helps to give a shadow effect to the button.
  6. font-size - Sets the font size of the text inside the button.
  7. border-radius - It helps to give rounded corners to the button.
  8. cursor - It helps to change the cursor when it is over the button.
  9. hover - It helps to change the style of the button when the cursor is over the button. It is also called pseudo-class.
CSS button style example

Let's now create some beautiful buttons with CSS!

List of 10 CSS Buttons

Here is a list of 10 CSS buttons that you can use in your projects. You can also use these buttons to create your own buttons.

1. Simple Button

Here is a simple button with a simple CSS code.

Example 1

.button-1 {
  background-color: #4CAF50;
  border: none;
  color: white;
  display: inline-block;
  padding: 15px 32px;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}
CSS
▶ Try it

Output:


2. Rounded Button

Use the border-radius property to create a rounded button. Here is a rounded button with a simple CSS code.

Example 2

.button-2 {
  border-radius: 12px;
}
CSS
▶ Try it

Output:


3. Button with Shadow

Use the box-shadow property to create a button with shadow. Box shadow takes values for offset-xoffset-yblur-radiusspread-radius and color.

Example 3

.button-3 {
  box-shadow: 5px 5px 5px #888888;
}
CSS
▶ Try it

Output:


4. Button with Border

Use the border property to create a button with a border. the border takes values for widthstyle, and color.

Example 4

.button-4 {
  border: 2px solid #008CBA;
}
CSS
▶ Try it

Output:


5. Button with Gradient

Use the background property to create a button with a gradient.

Use the linear-gradient function to create a linear gradient.

Example 5

.button-5 {
  background: linear-gradient(to right, #008CBA, #4CAF50);
}
CSS
▶ Try it

Output:


6. Button with hover effect

Use the :hover pseudo-class to create a button with hover effect.

Example 6

.button-6 {
  background-color: #008CBA;
  border: none;
  color: white;
  padding: 15px 32px;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}

.button-6:hover {
  background-color: #4CAF50;
}
CSS
▶ Try it

Output:


7. Capsule Shaped Button

Round the corners of a button to create a capsule shaped button.

Example 7

.button-7 {
  border-radius: 50px;
}
CSS
▶ Try it

Output:


8. Button shadow hover animation

The following button has a shadow animation when the mouse pointer hovers over it.

Example 8

.button-8:hover {
  box-shadow: inset -2px -2px 5px #f2b9ac,
              inset 2px 2px 5px #b06655;
}
CSS
▶ Try it

Output:


9. Button with shake animation

The following button has a shake animation when the mouse pointer hovers over it.

Example 9

.button-9:hover {
    animation: shake 0.15s;
    animation-iteration-count: 3;
}

@keyframes shake {
    0% { transform: translate(0, 0) }
    25% { transform: translate(5px, 0) }
    50% { transform: translate(0, 0) }
    75% { transform: translate(-5px, 0) }
    100% { transform: translate(0, 0) }
}
CSS
▶ Try it

Output:


10. Button skew on hover

The following button has a skew animation when the mouse pointer hovers over it.

Example 10

.button-10 {
    transition: transform 0.3s;
}

.button-10:hover {
    transform: skewX(-8deg);
}
CSS
▶ Try it

Output:

CSS COMBINATORS


CSS combinators are a combination of two or more other CSS selectors and create a relationship between them. The combinators also provide the location of the content in the HTML document and are used to target specific elements to style.

There are many different types of combinator selectors in CSS. Here are 8 most used of them:

  1. Descendant selector
  2. Adjacent sibling selector (+)
  3. General sibling selector (~)
  4. Child selector
  5. First child selector ( :first-child )
  6. Last child selector ( :last-child )
  7. Only child selector ( :only-child )
  8. Nth child selector ( :nth-child() )

1. Descendant selector

The descendant selector is used to select all the elements that are descendants of a specified element.

A descendant combinator is written by a combination of two or more selectors separated by a space. The first selector is the parent element and the second selector is the child element.

For example, div ul li will select all the li elements that are descendants of ul elements that are descendants of div elements.

Example

/* descendent selector */
div ul li{
    background-color: pink;
    margin-top: 10px;
}
CSS
▶ Try it

2. Adjacent sibling

The adjacent selector selects the elements that are adjacent to the specified selector. Here adjacent means immediately after the specified selector.

This combinator is written by a combination of other selectors separated by a plus (+).

For example, h2 + p will select all the p elements that are immediately after by h2 elements.

Example

/* adjacent sibling selector */
h2 + p {
    font-size: 1.5em;
    background-color: pink;
}
CSS
▶ Try it

3. General sibling selector

The general sibling selector selects all the sibling elements that follow the first selector element.

This combinator is written by a combination of other selectors separated by a tilde (~).

For example div ~ p will select all the p elements that are siblings of div elements.

Example

div ~ p{
    font-size: 1.5em;
    background-color: pink;
}
CSS
▶ Try it

4. Child selector

The child selector selects all the elements that are the child of the specified selector. Here adjacent means immediately after the specified selector.

This combinator is written by a combination of other selectors separated by greater than (>).

For example div > p will select all the p elements that are the child of div elements.

Example

div > p{
    font-size: 1.5em;
    background-color: pink;
}
CSS
▶ Try it


5. First child selector

The first child selector selects all the elements that are the first child of the specified selector.

It is written as :first-child.

For example div :first-child will select all the first child elements of div elements.

Example

div :first-child{
    font-size: 1.5em;
    background-color: pink;
}
CSS
▶ Try it

6. Last child selector

The last child selector selects all the elements that are the last child of the specified selector.

It is written as :last-child.

For example div :last-child will select all the last child elements of div elements.

Example

div :last-child{
    font-size: 1.5em;
    background-color: pink;
}
CSS
▶ Try it


7. Only child selector

The only child selector selects all the elements that are the only child of the specified selector.

It is written as :only-child.

For example div :only-child will select all the only child elements of div elements. If there are more than one child element then it will not select any element.

Example

div :only-child{
    font-size: 1.5em;
    background-color: pink;
}
CSS
▶ Try it

8. Nth child selector

The nth-child selector selects all the elements that are the nth child of the specified selector.

It is written as :nth-child().

For example div :nth-child(2) will select all the second child elements of div elements.

Example

div :nth-child(2){
    font-size: 1.5em;
    background-color: pink;
}
CSS
▶ Try it

CSS Specificity


CSS specificity is a set of rules that determines which CSS property values are applied to an element. It is used to resolve conflicts when more than one rule applies to a particular element. It is a way to determine which style declaration has the highest priority.

Specificity is based on the matching rules of CSS selectors. The more specific selector is the higher its priority. The browser applies the CSS rule with the highest priority.

If you have trouble understanding the above definition, let's take an example.

Let's say we have a p element with a class .represent and an id #represent. We have two CSS rules for this element.

/* class selector */
.represent { color: green }
/* id selector */
#represent { color: red }
CSS

Now, what color will be applied to the p element? The answer is red. Because the id selector has a higher specificity than the class selector.

CSS selectors are provided with different values, ID has higher value than class. If multiple CSS rules are pointing to the same element then on the basis of those selector values CSS rules are ranked.


CSS Specificity Rules

On the basis of different selectors specificity value is given as follows:

  • inline style - Inline style has the highest value of specificity among other selectors. It is 1000 and can be represented as (1, 0, 0, 0)
  • id - ID has the second highest specificity value. It is 100 and can be represented as (0, 1, 0, 0)
  • class, pseudo-class, attribute selector - These have the third highest value of specificity among other selectors. It is 10. Can be represented as (0, 0, 1, 0)
  • element or pseudo-element - These have the lowest specificity value. It is 1 and can be represented as (0, 0, 0, 1)
Calculating specificity in CSS
Calculating specificity in CSS


Calculation of specificity

To calculate the specificity of a CSS selector, we need to add the values of each selector type. For example, if we have a selector #id.class, then the specificity value will be (0, 1, 1, 0) because it has one id selector and one class selector. It can also be represented as 0110.

Let's take another example. If we have a selector p.class, then the specificity value will be (0, 0, 1, 1). It can also be represented as 0011.

Example 1:

Example

<style>
  /* specificity = 0,0,1,1 = 11 */
  p.color {
    color: blue;
  }
  /* specificity = 0,0,0,2 = 2 */
  div p {
    color: red;
    background-color: light-yellow;
  }
</style>

<div>
  <p class="color">I am blue because specificity of class selector is more than element selector.</p>
</div>
HTML
▶ Try it

Here in the above example, both CSS rules are pointing to the same element. But the CSS rule with class selector has a higher specificity value than the CSS rule with element selector. So, the color of the p element will be blue.


# Example 2

Example

<style>
  /* specificity = 0,0,1,2 = 12 */
  div p.add-color {
    color: blue;
  }
  /* specificity = 0,1,0,1 = 101 */
  p#id-color {
    color: red;
  }
</style>

<p id="id-color" class="class-color">I am blue because specificity of id selector is more than class selector.</p>
HTML
▶ Try it

Here in the above example, both CSS rules are pointing to the same element. But the CSS rule with an ID selector has a higher specificity value than the CSS rule with a class selector. So, the color of the p element will be red.


Example 3:

Example

<style>
  #id-color p {
    color: blue;
  }
</style>

<p style="color:red">This paragraph is red.</p>
HTML
▶ Try it

Inline CSS has the highest specificity value. So, the color of the p element will be red.


Equal specificity

When there are two CSS rules having the same specificity value then the rule that is defined lower in the style sheet is applied.

Example

p {
    color: blue;
}
p {
    color: red;
}
CSS
▶ Try it

  1. What is the specificity in CSS?

    Specificity is a value that is used to determine which CSS rule will be applied to an element. It is calculated by adding the values of each selector type. The selector with a higher specificity value will be applied.

  2. Why use specificity in CSS?

    When there are two or more than 2 CSS rule set for the same element, the browser gets confused about which CSS rule to apply. So, it uses specificity to determine which CSS rule to apply.

  3. What has the highest specificity in CSS?

    Inline CSS has the highest specificity value. It is 1000.

  4. What is the lowest specificity in CSS?

    Element selector has the lowest specificity value. It is 1.

  5. What is the order of specificity in CSS?

    Inline CSS > ID selector > Class selector > Element selector

  6. What is the specificity value of universal selector?

    Universal selector (*) has a specificity value of 0.

CSS transform Property - 2D and 3D


Introduction

The transform property is used to transform an element in 2D or 3D space. It allows you to rotatescaleskew, or translate an element. This property accepts a CSS function or a list of functions.

This property visually transforms an element without changing its layout. It can be used to create animations, icons, and other visual effects.


Syntax

The syntax of the transform property is given below:

div {
    transform: none | transform-functions;
}
CSS

The transform property accepts the following values:

  • none - This value specifies that no transformation should be applied.
  • transform-functions - This value specifies a list of one or more transformation functions.

CSS transform Functions

You can see in the above syntax that the transform property accepts a list of one or more transformation functions. Let's see the list of transformation functions with their use with examples.


2D transform Functions

  1. translate() - This function is used to translate an element along the X and Y axis.

    • translateX()
    • translateY()
    • translateZ()
  2. scale() - This function is used to scale an element along the X and Y axis.

    • scaleX()
    • scaleY()
    • scaleZ()
  3. rotate() - This function is used to rotate an element along the X and Y axis.

    • rotateX()
    • rotateY()
    • rotateZ()
  4. skew() - This function is used to skew an element along the X and Y axis.

    • skewX()
    • skewY()
  5. matrix() - This function is used to apply a 2D transformation to an element.


3D transform Functions

  1. translate3d() - This function is used to translate an element along the X, Y, and Z axis.

  2. scale3d() - This function is used to scale an element along the X, Y, and Z axis.

  3. rotate3d() - This function is used to rotate an element along the X, Y, and Z axis.

  4. matrix3d() - This function is used to apply a 3D transformation to an element.

  5. perspective() - This function is used to define the perspective for a 3D transformed element.


2D transform Functions

1. translate() Function

The translate() function is used to move an element up, down, left, or right.

It accepts two parameters, the first parameter x is used to move the element along the X axis, and the second parameter y is used to move the element along the Y axis.

For example translate(50px, 20px) will move the element 50px along the X axis and 20px along the Y axis.

Example

div {
    /* Move the element 50px along the X-axis
    and 20px along the Y-axis */
    transform: translate(50px, 20px);
}
CSS
▶ Try it

Visualize the output:

Move:
x=50px, y=20px

1.1 translateX() Function

The translateX() function is used to move an element along the X-axis.

It accepts only one parameter (x). For example translateX(50px) will move the element 50px along the X axis.

Example

div {
    /* Move the element 50px along the X-axis */
    transform: translateX(50px);
}
CSS
▶ Try it

Visualize the output:

Move:
x=50px

1.2 translateY() Function

The translateY() function is used to move an element along the Y axis.

It accepts only one parameter (Y). For example translateY(20px) will move the element 20px along the Y axis.

Example

div {
    /* Move the element 20px along the Y-axis */
    transform: translateY(20px);
}
CSS
▶ Try it

Visualize the output:

Move:
y=20px

2. scale() Function

The scale() function is used to change the size of an element.

It accepts 2 parameter values x and y. The first parameter changes the width of the element, and the second parameter changes the height of the element.

For example scale(1.5, 0.5) will increase the width of the element by 50% and decrease the height of the element by 50%.

Example

div {
    /* Increase the width of the element by 50%
    and decrease the height of the element by 50% */
    transform: scale(1.5, 0.5);
}
CSS
▶ Try it

Visualize the output:

Scale:
x=1.5, y=0.5


2.1 scaleX() Function

The scaleX() function just changes the width of the element.

Example

div {
    /* Increase the width of the element by 50% */
    transform: scaleX(1.5);
}
CSS
▶ Try it

Visualize the output:

Scale:
x=1.5

2.2 scaleY() Function

The scaleY() function just changes the height of the element.

Example

div {
    /* Increase the height of the element by 50% */
    transform: scaleY(1.5);
}
CSS
▶ Try it

Visualize the output:

Scale:
y=1.5

3. rotate() Function

The rotate() function is rotates an element clockwise or counter-clockwise around its center.

It accepts 1 parameter value angle. The parameter value is the angle by which the element is rotated.

For example rotate(45deg) will rotate the element by 45 degrees.

Example

div {
    /* Rotate the element by 45 degrees */
    transform: rotate(45deg);
}
CSS
▶ Try it

Visualize the output:

Rotate:
45deg

3.1 rotateX() Function

The rotateX() function rotates an element clockwise or counter-clockwise around its X-axis.

Example

div {
    /* Rotate the element by 45 degrees around its X-axis */
    transform: rotateX(45deg);
}
CSS
▶ Try it

Visualize the output:

Rotate:
x=45deg

3.2 rotateY() Function

The rotateY() function rotates an element clockwise or counter-clockwise around its Y-axis.

Example

div {
    /* Rotate the element by 45 degrees around its Y-axis */
    transform: rotateY(45deg);
}
CSS
▶ Try it

Visualize the output:

Rotate:
y=45deg

3.3 rotateZ() Function

The rotateZ() function rotates an element clockwise or counter-clockwise around its Z-axis.

Example

div {
    /* Rotate the element by 45 degrees around its Z-axis */
    transform: rotateZ(45deg);
}
CSS
▶ Try it

Visualize the output:

Rotate:
z=45deg

4. skew() Function

The skew() function skews an element along the X and Y axes.

For example skew(45deg, 45deg) will skew the element by 45 degrees along the X and Y axes.

Example

div {
    /* Skew the element by 45 degrees along the X and Y axes */
    transform: skew(45deg, 45deg);
}
CSS
▶ Try it

Visualize the output:

Skew:
x=45deg, y=45deg


4.1 skewX() Function

The skewX() function skews an element along the X-axis.

Example

div {
    /* Skew the element by 45 degrees along the X-axis */
    transform: skewX(45deg);
}
CSS
▶ Try it

Visualize the output:

Skew:
x=45deg

4.2 skewY() Function

The skewY() function skews an element along the Y-axis.

Example

div {
    /* Skew the element by 45 degrees along the Y-axis */
    transform: skewY(45deg);
}
CSS
▶ Try it

Visualize the output:

Skew:
y=45deg

5. matrix() Function

The matrix() function defines a 2D transformation using a matrix of six values.

The values represented as matrix(scaleX(), skewY(), skewX(), scaleY(), translateX(), translateY()).

For example matrix(1.5, 1, 0.5, 0.5, 50, 50) will scale the element by 1.5 along the X-axis, 0.5 along the Y-axis, skew the element by 1 along the X-axis and 0.5 along the Y-axis, and translate the element by 50px along the X-axis and 50px along the Y-axis.

Example

div {
    transform: matrix(1.5, 1, 0.5, 0.5, 50, 50);
}
CSS
▶ Try it

Visualize the output:

Matrix:
scaleX=1.5, skewY=2, skewX=5, scaleY=0.5, translateX=50, translateY=50

3D transform Function

3D transform functions are used to transform elements into three-dimensional space.

1. translate3d() Function

The translate3d() function translates an element along the X, Y, and Z axes.

Before using the translate3d() function, you must set the transform-style property to preserve-3d for the element to be transformed into three-dimensional space.

Also, the parent element must have a perspective property set to a value other than none to create a three-dimensional space.

Example

.parent {
    /* Set the perspective property to
    create a three-dimensional space */
    perspective: 500px;
}

div.child {
    /* Set the transform-style property to
    preserve-3d to transform the element
    in three-dimensional space */
    transform-style: preserve-3d;

    transform: translate3d(50px, 50px, 150px);
}
CSS
▶ Try it

Visualize the output:

Translate:
x=50px, y=50px, z=150px

2. rotate3d() Function

The rotate3d() function rotates an element along the X, Y, and Z axes.

The function takes four values represented as rotate3d(x, y, z, angle). Where x, y and z are describes the coordinate of the vector denoting the axis of rotation which could be between 0 and 1.

Example

div {
    transform: rotate3d(1, 1, 1, 60deg);
}
CSS
▶ Try it

Visualize the output:

Rotate:
x=1, y=1, z=1, angle=60deg

Multiple Transform Functions

You can use multiple transform functions in a single transform property.

The order of the functions is important. The last function will be applied first.

Example

div {
    transform: scale(1.5, 0.5) rotate(60deg);
}
CSS
▶ Try it

Visualize the output:

Translate:
x=50px, y=50px
Rotate:
angle=60deg

Conclusion

In this tutorial, you have learned about the CSS transform property and its various functions.

You can use the transform property to translate, rotate, scale, and skew elements.

You can also use the transform property to create three-dimensional effects.

Next, you will learn about the CSS transition property.

Learn CSS Animation


CSS animation is a great way to add some life to your website. It allows you to animate elements without using JavaScript or Flash. You can animate borders, backgrounds, and even transform elements. The best part is that you can control the speed of the animation.

Here is a simple example of an animation that changes the background color of an <div> element:

Let's learn how to create animation in CSS.


How to Create CSS Animation

These are the steps to create CSS animation:

  1. Define the animation with the @keyframes rule.
  2. Apply the animation to an element using the animation property.
  3. Specify the animation name, duration, timing function, delay, and the number of iterations.

We will learn everything in detail but before that let's see some examples of animation.

Example

div {
    animation: mycolor 4s infinite;
}

@keyframes mycolor {
    from {background-color: red;}
    to {background-color: yellow;}
}
CSS
▶ Try it

Output:

The above animation changes the background color of the <div> element from red to yellow.

To set the animation to the element we used the animation property and set the animation name 'mycolor' to the element. The animation name is the same as the name of the @keyframes rule.


@keyframes Rule

The @keyframes rule is used to define the animation. It contains the animation name, any animation breakpoints, and the properties intended to be animated.

The animation will move from one state to the next, and then back to the first state, and then to the next state, and so on as defined in the @keyframes rule.

To define keyframes, you use the @keyframes followed by the name of the animation name.

Here is the syntax of @keyframes rule:

@keyframes animation-name {
    0%   {property: value; ...}
    25%  {property: value; ...}
    50%  {property: value; ...}
    100% {property: value; ...}
} /* you can use any percentage value */

/* Or */

@keyframes animation-name {
    from {property: value; ...}
    to {property: value; ...}
}
CSS

@keyframes is the block where you define how the animation will look like. You can create as many breakpoints as you want.

Later just use this animation name in the animation property to apply the animation to any element.

Let's see some examples of @keyframes rule.

Example

div {
    animation: my-animation 2s infinite;
}

@keyframes my-animation {
    0% {
      background-color: red;
      transform: rotate(0deg);
    }
    25% {
      background-color: green;
      transform: rotate(90deg);
    }
    50% {
      background-color: blue;
      transform: rotate(180deg);
    }
    75% {
      background-color: yellow;
      transform: rotate(270deg);
    }
    100% {
      background-color: red;
      transform: rotate(360deg);
    }
}
CSS
▶ Try it

Output:

The above animation changes the background color of the <div> element from red to yellow and rotates the element from 0 to 360 degrees.

Note: If your animation repeats then for smooth animation you should end your animation with the same state as the starting state. You can see the above example starts with red color and ends with red color also starts with 0 degree and ends with 360 degrees (0deg is the same as 360deg when rotated).


CSS Animation Properties

The @keyframes defined the animation but to apply the animation to the element we need to use the animation property.

There are many properties that can be used to control the animation. Here are some of the most important properties:

  1. animation-name - Specifies the name of the animation to use.
  2. animation-duration - Specifies how long time the animation should take to complete one cycle. Example 1s2s, etc (s means seconds).
  3. animation-timing-function - Specifies the speed curve of the animation. Example lineareaseease-inease-outease-in-out.
  4. animation-delay - Specifies a delay for the start of an animation. Example 1s2s, etc.
  5. animation-iteration-count - Specifies the number of times an animation should be played. Example infinite12, etc.
  6. animation-direction - It tells the animation whether to play forwards, backward, or in alternate cycles.
  7. animation-fill-mode - It specifies a style for the target element when the animation is not playing (before it starts, after it ends, or both).
  8. **animation - This is a shorthand property for all the above properties.

Let's see an example that covers all the above properties.

CSS Example animation

Here is working code for the above example.

Example

div {
    animation-name: change-color;
    animation-duration: 2s;
    animation-iteration-count: infinite;
    animate-direction: alternate;
    animation-timing-function: ease-in-out;
    animation-delay: 0s;
}

@keyframes change-color {
    0% {
      background-color: red;
      transform: translate(0, 0);
    }
    25% {
      background-color: green;
      transform: translate(0, 150px);
    }
    50% {
      background-color: blue;
      transform: translate(150px, 150px);
    }
    75% {
      background-color: yellow;
      transform: translate(150px, 0);
    }
    100% {
      background-color: red;
      transform: translate(0, 0);
    }
}
CSS
▶ Try it

Set Number of Times to Repeat Animation

By default, the animation will repeat only 1 time. To set the number of times to repeat the animation, use the animation-iteration-count property.

You can set the number of times to repeat the animation by using a number or the keyword infinite.

Here is an example of repeating the animation 3 times.

Example

div {
    animation-name: change-color;
    animation-duration: 2s;
    animation-iteration-count: 3;
}
CSS
▶ Try it

Set Direction of Animation

The animation-direction property specifies whether the animation should play forwards, backward, or in alternate cycles.

In alternate cycle mode, animation first plays forwards, then backwards, then forwards again, and so on.

Example

div {
    animation-name: change-color;
    animation-duration: 2s;
    animation-iteration-count: infinite;
    animation-direction: alternate;
}
CSS
▶ Try it

Set Speed Curve of Animation

The animation-timing-function property specifies the speed curve of the animation. The speed curve defines how the animation will progress over the duration of each cycle.

Possible values for speed curve are:

  • ease - specifies a transition effect with a slow start, then fast, then end slowly (this is the default)
  • linear - specifies a transition effect with the same speed from start to end
  • ease-in - specifies a transition effect with a slow start
  • ease-out - specifies a transition effect with a slow end
  • ease-in-out - specifies a transition effect with a slow start and end
  • cubic-bezier(n,n,n,n) - lets you define your own values in a cubic-bezier function

Example

div {
    animation-name: change-color;
    animation-duration: 2s;
    animation-iteration-count: infinite;
    animation-timing-function: linear;
}
CSS
▶ Try it

Animation shorthand

The animation property is a shorthand property for all the animation properties.

Syntax:

animation: name duration timing-function delay iteration-count direction;
CSS

Here is an example of using the animation property.

Example

div {
    animation: change-color 2s linear 0s infinite alternate;
}
CSS
▶ Try it

Quiz - CSS Animation Quiz

Know CSS animation property! Why not test your knowledge by picking answers to some multiple-choice questions?

Quiz Image
does CSS animation slow down the website?
Which CSS property is used to describe how an animation is to play?
What is the default value of the animation-iteration-count property?
Which of the following is not a valid value for the animation-fill-mode property?
What is the purpose of the @keyframes rule in CSS animation?
How can you specify the starting point of a CSS animation?
Which of the following is not a valid value for the animation-timing-function property?
How can you control the speed of a CSS animation?
How can you specify the number of times a CSS animation should be played?
How can you specify multiple animation names on a single element?

Variables in CSS


CSS variables are user-defined variables that can store any CSS values like numbers, strings, or color. It helps in maintaining consistency throughout the entire webpage. In this tutorial, we are going to learn the Basics of CSS Variable with various Examples.

CSS variables are used to store a value that can be used frequently in the HTML document.

The benefit of using CSS variables is that we can use the same variable in multiple places in the document. We can also change the value of the variable in one place and it will be reflected in all the places where the variable is used.

Set Variables

The variables are defined by a name preceded by a double dash and a value is assigned to the variable after a colon. Example: --nav-color: red

:root{
    --nav-color: red;
    --link-color: white;
}
CSS

Access Variables

variables can be accessed by var(--variable name) notation. Just prepend a specific variable name to var() function.

/* using variable inside a selector */
a {
    color: var(--link-color);
}
CSS

Let's see the following example to understand how CSS variable work.

Example

<style>
    :root{ --my-color: red; }
</style>

<p style="color: var(--my-color)">This paragraph is using the CSS variable.</p>
HTML
▶ Try it

CSS variable scope

Any variable that we define in CSS has a scope value. Beyond a variable's scope is not accessible.

You just can not define variables anywhere in their document. Based on its use you can define it in three ways global and local.


1. Global scope

A variable that is defined globally can be accessed anywhere in the linked document.

A global variable is defined inside :root selector.

Example

:root {
  --my-background: orange;
  --my-padding: 15px;
  --my-border: #ccc 2px solid;
}

.box {
  background-color: var(--my-background);
  padding: var(--my-padding);
}

p {
  padding: var(--my-padding);
  border: var(--my-border);
}
CSS
▶ Try it

2. Local scope

A variable is defined locally by defining it within the code block of a specific selector.

A local variable can only be used within the selector it is defined.

Example

.box{
    --my-background: orange;
    --my-padding: 15px;
    --my-margin: 10px;
    background-color: var(--my-background);
    padding: var(--my-padding);
    margin: var(--my-margin);
}
CSS
▶ Try it

CSS variable inheritance

When you define a variable inside a selector, the variable is accessible inside that selector and its child elements.

Let's see the following example to understand how CSS variable inheritance work.

Example

.box{
    --my-border: #ccc 2px solid;
    --my-padding: 15px;

    border: var(--my-border);
    padding: var(--my-padding);
}

.box p {
    border: var(--my-border);
    padding: var(--my-padding);
}
CSS
▶ Try it

CSS variable overriding

When you define a variable inside a selector, the variable is accessible inside that selector and its child elements. If you define a variable with the same name inside a child element, the variable will be overridden.

Overriding is the process of changing the value of a variable. It does not cause any error just the value of the variable is changed.

Let's look at the following example to understand how CSS variable overriding works.

Example

:root {
    --my-border: #ccc 2px solid;
    --my-padding: 15px;
}

div {
    border: var(--my-border);
    padding: var(--my-padding);
}

p {
    --my-border: red 2px solid;
    --my-padding: 10px;

    border: var(--my-border);
    padding: var(--my-padding);
}
CSS
▶ Try it

CSS Pagination


CSS pagination is a way by which web users can easily jump anywhere in a large collection of related web pages. Pagination is generally in number form, which specifies the nth webpage from starting.

On websites with a large number of web pages, they sort the web pages in this manner.

There are many ways to implement pagination in CSS. We will see some of them in this tutorial.


CSS Pagination Example

Here is a simple example of CSS pagination.

Simple pagination

This is a simple pagination show next and previous buttons and a few pages in between.

  • HTML
.simple-pagination {
  list-style: none;
  padding: 0;
  margin: 0;
}

.simple-pagination li {
  display: inline-block;
  margin: 0 1px;
}

.simple-pagination li a {
  display: inline-block;
  padding: 10px 15px;
  background: #eebe57;
  color: #020202;
  text-decoration: none;
}
CSS
▶ Try it

Output:


Round pagination

To create rounded pagination you can use the border-radius property.

The border-radius property is used to create rounded corners on an element. To create a circle you can use 50% value.

  • HTML
.simple-pagination {
  list-style: none;
  padding: 0;
  margin: 0;
}

.simple-pagination li {
  display: inline-block;
  margin: 0 1px;
}

.simple-pagination li a {
  display: inline-block;
  padding: 10px 15px;
  background: #eebe57;
  color: #020202;
  text-decoration: none;
  /* round border */
  border-radius: 50%;
}
CSS
▶ Try it

Output:


Pagination with Hover effect

The hover effect of pagination is initiated when you take the mouse pointer over the pagination buttons.

To define the hover effect we need to add :hover CSS property for the pagination. Let's see in the example below.

  • HTML
.simple-pagination {
  list-style: none;
  padding: 0;
  margin: 0;
}

.simple-pagination li {
  display: inline-block;
  margin: 0 1px;
}

.simple-pagination li a {
  display: inline-block;
  padding: 10px 15px;
  background: #eebe57;
  color: #020202;
  text-decoration: none;
  transition: all 0.3s ease;
}

.simple-pagination li a:hover {
  background: #da883b;
  margin: 0 2px;
  transition: all 0.3s ease;
}
CSS
▶ Try it

Output:


Active Pagination

For quick knowledge for the user which page he is on currently, we make the page number representing that web page active on pagination.

To show that this pagination block is active we use a sharp background-color for that section. Let's see an example.

  • HTML
.simple-pagination {
  list-style: none;
  padding: 0;
  margin: 0;
}

.simple-pagination li {
  display: inline-block;
  margin: 0 1px;
}

.simple-pagination li a {
  display: inline-block;
  padding: 10px 15px;
  background: #eebe57;
  color: #020202;
  text-decoration: none;
}

.simple-pagination .active {
  background: #2e2e2e;
  color: #eebe57;
}
CSS
▶ Try it

Output:


Centered Pagination

To beautify a web page with pagination it's better if our pagination is in the center of the page.

To align the pagination in the center in a div block you can use many ways. Here we are using the text-align property to align the pagination in the center.

  • HTML
.simple-pagination {
  list-style: none;
  padding: 0;
  margin: 0;
  text-align: center;
}

.simple-pagination li {
  display: inline-block;
  margin: 0 1px;
}

.simple-pagination li a {
  display: inline-block;
  padding: 10px 15px;
  background: #eebe57;
  color: #020202;
  text-decoration: none;
}
CSS
▶ Try it

Output:

CSS Flexbox Tutorial


Flexbox is a 1-dimensional layout model in CSS. It is a module that comes with lots of CSS properties and can be used to create complex layouts.

    Table Of Contents

  1. What is CSS flexbox?
  2. Understanding Flexbox
  3. How to use flexbox?
  4. All CSS Flexbox Properties
  5. Flexbox CSS properties for container itself (Parent)
    1. flex-direction
    2. flex wrap
    3. flex-flow
    4. justify content
    5. align-items
    6. align content
  6. Flexbox CSS properties for container's items (Child)
    1. Flexbox order
    2. Flex grow
    3. Flex basis
    4. Flex shrink
    5. Flex
    6. align self

What is CSS flexbox?

CSS flexbox is a one-dimensional web layout method that is used to arrange HTML containers in a row or column.

Flexbox or CSS flexbox allows the HTML elements to get automatically arranged depending on screen sizes.

It is a module that comes with lots of CSS properties and can be used to create complex layouts.

CSS flexbox tutorial

The main idea behind CSS flexbox is to give the container ability to change its item's size automatically to best fit in available space.

Here are 3 images that show how HTML containers arranged using flexbox automatically fits themselves according to device width.

CSS flexbox makes web developers life easy to design and arrange HTML elements in the webpage.

Before CSS flexbox it was quite difficult to fit and align-items on a webpage. The items were mostly laid out using float and position properties. Even though using just float and position properties we were unable to perform many tasks like:

  • Aligning items vertically
  • Making child element take up equal space even with unequal length of items


Understanding CSS flexbox

CSS flexbox is not a property its a module ( a W3C recommendation as of Oct 2017 ). It involves a whole set of CSS properties, some of its property is for the container itself on which flexbox is applied and some are for its child elements.

To understand flexbox you have to think in terms of 2 axes -

  • the main axis: The horizontal axis
  • the cross axis: The verticle axis

flexbox axis diagram
Flexbox axis diagram

The items of the container will either lie along the main axis or the cross axis and these items can be placed at a various place along this 2 axis.

So now we have an idea, that container will align its item in 2 direction horizontal and verticle and along with these 2 directions, it will be spread in various ways, like align in the start, in the end, in middle, or spread in other ways.


How to use flexbox?

To start with flexbox we first need to define flexbox in our parent element so that other properties of flexbox could be used by the parent as well as a child element.

To make the container a flexible box define display: flex or display: inline-flex to the container:

  • display: flex makes the container itself behave like a block element
  • display: inline-flex makes container behave like inline element

Example

.container {  
  display: flex; /* or inline-flex */
}
CSS
▶ Try it
CSS flexbox example
1
2
3
4
5

You can see in the output above adding display: flex property creates a flex container and by default, its item is aligned in the horizontal direction.


All CSS Flexbox Properties

Since you know now how to create a flexbox in CSS, its time to know all the CSS properties associated with flexbox.

The flexbox properties can be divided into 2 parts:

  1. CSS that is applied on the container itself (Parent) - Flexbox properties which is applied on the container itself are as follows:

    1. flex-direction
    2. flex-wrap
    3. flex-flow
    4. justify-content
    5. align-items
    6. align-content
  2. CSS that is applied on items of the container (Child) - Flexbox properties which is applied on the items of the container are as follows:

    1. order
    2. flex-grow
    3. flex-shrink
    4. flex-basis
    5. flex
    6. align-self

Now let's see each property and what effect it creates with example.


Flexbox CSS that is applied to container itself (Parent)

Let's look at all the flexbox property applied to the flexbox container.

1. CSS flex-direction

Flexbox module provides a property called flex-direction which specify what direction the children are laid out in.

flex-direction has 4 different values:

  1. row: It aligns flexbox items from left to right. It is the default value of flex-direction.
  2. row-reverse: It aligns flexbox items from the right end of the container to the left end.
  3. column: It aligns flexbox items from top to bottom in the flexbox container.
  4. column-reverse: It aligns flexbox items from bottom to top in the flexbox or container.

.container {
  display: flex;
  flex-direction: row; /* or row-reverse | columns | column-reverse */
}
CSS

flex direction in flexbox
Flexbox direction
CSS flexbox direction example
1
2
3
4
5

Let's see flex-direction property with each value with examples.

I. flex direction row

If you want your container elements to be in a row then use flex-direction: row property. It is also the default value of the flex-direction property, so you do not have to explicitly add it.

Possible mistake: Just applying flex-direction property on any container won't work you have use it on the container with flexbox (display: flex)

.container {  
  display: flex;  
  flex-direction: row;  /* Default value */
}
CSS
▶ Try it

Output:

1
2
3
4
5

II. flex direction row reverse

To set container item in a row but in reverse direction use flex-direction: row-reverse property.

This property cause container items to start from the end of the container in reverse order.

.container {  
  display: flex;  
  flex-direction: row-reverse;  
}
CSS
▶ Try it

Output:

1
2
3
4
5

III. flex-direction column

The flex-direction: column aligns the flexbox items in columns i.e from top to bottom.

.container {  
  display: flex;  
  flex-direction: column;  
}
CSS
▶ Try it

Output:

1
2
3

IV. flex-direction column reverse

The flex-direction: column-reverse aligns the flexbox items in columns in reverse order i.e from bottom to top.

.container {  
  display: flex;  
  flex-direction: column-reverse;  
}
CSS
▶ Try it

Output:

1
2
3

2. CSS flex-wrap

flex-wrap property is used to define whether the flex items are aligned in a single row or the items can flow to multiple rows.

flex-wrap property set values of wrapping items. There are three values that could be set for flex-wrap property nowrapwrap and wrap-reverse.

  1. nowrap: It forces flex items to be in the same row. It is the default value for flex-wrap.
  2. wrap: It let flex items to flow to the next row if there is no space to fit in the same row.
  3. wrap-reverse: It specifies that flex items can flow to multiple rows but items will start from the bottom of the flexbox and after fill that it will flow to the upper row.
flex-wrap property
flex-wrap property
CSS flexbox wrap example
1
2
3
4
5
6
7
8
9
10

Let's see examples of each property value.

I. flex-wrap nowrap ( default )

The flex-wrap: nowrap property forces container items to stay in the same row. It items do not fit in the container then it is simply overflown.

.container {  
  display: flex;  
  flex-wrap: nowrap;  /* default value */
}
CSS
▶ Try it

Output:

1
2
3
4
5
6
7
8
9
10

II. flex-wrap wrap

The flex-wrap: wrap property let the items to flow to next row if it does not fit in the container.

.container {  
  display: flex;  
  flex-wrap: wrap;  
}
CSS
▶ Try it

Output:

1
2
3
4
5
6
7
8
9
10

III. flex-wrap wrap-reverse

The flex-wrap: wrap-reverse property let the items to flow to the next row but in reverse order, i.e item will start from the bottom of the container and will flow in an upward direction.

.container {  
  display: flex;  
  flex-wrap: wrap-reverse;  
}
CSS
▶ Try it

Output:

1
2
3
4
5
6
7
8
9
10

3. flex-flow CSS

The flex-flow property is shorthand for flex-direction and flex-wrap.

Combining both flex-direction and flex-wrap property the flex-flow property defines the cross-axis flow of the container.

The default value of flex-flow is row nowrap.

.flow1 {
  display: flex;
  flex-flow: column wrap-reverse;
  height: 400px; /* limiting height to see effect */
}

.flow2 {
  display: flex;
  flex-flow: row wrap;
}
CSS
▶ Try it
CSS flexbox flow example
1
2
3
4
5
6
7
8
9
10

4. justify-content CSS

The justify-content property aligns flex items along the X-axis (horizontally) also known as the main axis in the flexbox. All flex line's items align horizontally according to justify-content value.

The justify-content property has 6 different values flex-startflex-endcenterspace-aroundspace-evenly and space-between.

  1. flex-start: Aligns items horizontally to the start of the container (default value).
  2. flex-end: Aligns items horizontally to the end of the container.
  3. center: Aligns items horizontally to the center of the container.
  4. space-around: Aligns items horizontally equally distributed.
  5. space-evenly: Items are so aligned that the space between container and item is the same as the space between items.
  6. space-between: Aligns items horizontally between the start and end of the container. The first row starts from the left and the last row touches the right.
justify content CSS
justify-content CSS

CSS justify content example
1
2
3

Let's see examples of each value.

I. justify-content flex-start

This flex-start is the default value of the justify-content property, it aligns container items horizontally to the start of the container.

.container {  
  display: flex;  
  justify-content: flex-start;  
}
CSS
▶ Try it

Output:

1
2
3
4
5

II. justify-content flex-end

This flex-end value of the justify-content property aligns container items horizontally to the end of the container.

.container {  
  display: flex;  
  justify-content: flex-end;  
}
CSS
▶ Try it

Output:

1
2
3
4
5

III. justify-content center

This center value of justify-content property aligns container items horizontally to the center of the container.

.container {  
  display: flex;  
  justify-content: center;  
}
CSS
▶ Try it

Output:

1
2
3
4
5

IV. justify-content space-around

This space-around value of justify-content property aligns container items horizontally to the end of the container.

.container {  
  display: flex;  
  justify-content: space-around;  
}
CSS
▶ Try it

Output:

Aligns items horizontally and equally distributed.

1
2
3
4

V. justify-content space-evenly

This space-evenly value of justify-content aligns container items horizontally evenly in the container, the space between the items is equal to the space between items and the container.

.container {  
  display: flex;  
  justify-content: space-evenly;
}
CSS
▶ Try it

Output:

1
2
3
4

VI. justify-content space-between

This space-between value of justify-content property aligns container items horizontally between the start and endpoint of the container, both end item touches the container ends.

.container {  
  display: flex;  
  justify-content: space-between;  
}
CSS
▶ Try it

Output:

1
2
3
4

5. align-items CSS

The align-items property aligns the container items along Y-axis (Vertically), also known as a cross-axis in flexbox.

Note: The align-items is a single-line property if your container item wraps to the new line then it won't work for the new line. To align items as a whole use the align-content property.

The align-items property has 5 different values flex-startflex-endcenterbaseline and stretch.

  1. stretch - It stretches the flex items along the container to fill the container but min-width and max-width are applied to items if mentioned. It is the default value of the align-item property.
  2. flex-start - It aligns flex items to the top of the container.
  3. flex-end - It aligns flex items to the bottom of the container.
  4. center - It aligns flex items in the center of the container.
  5. baseline - It aligns flex items in such a way that their baseline aligns.
align-items CSS
align-items CSS

CSS align items example
1
2
3

Let's see an example of each value of this property.

I. align-items stretch

The flex-end value align-items property stretches the items along Y-axis and covers 100% height unless the min or max value is defined.

.container {  
  display: flex;  
  align-items: stretch;  /* Default value */
}
CSS
▶ Try it

Output:

1
2
3
4
5

II. align-items flex-start

The flex-start value align-items property aligns the items to the top of the container.

.container {  
  display: flex;  
  align-items: flex-start;  
}
CSS
▶ Try it

Output:

1
2
3
4
5

III. align-items flex-end

The flex-end value align-items property aligns the items to the bottom of the container. The items start from the bottom of the container.

.container {  
  display: flex;  
  align-items: flex-end;  
}
CSS
▶ Try it

Output:

1
2
3
4
5

IV. align-items center

The center value align-items property aligns the items to the center of the container along the Y-axis.

.container {  
  display: flex;  
  align-items: center;  
}
CSS
▶ Try it

Output:

1
2
3
4
5

V. align-items baseline

The baseline value align-items property aligns the items along their baseline.

.container {  
  display: flex;  
  align-items: baseline;  
}
CSS
▶ Try it

Output:

1

2

3

4

5


6. align content CSS

The align-content property works the same as the align-content property along Y-axis but the only difference in both is that instead of aligning flex items align-content aligns the flex container's line as a whole

The align-content is multiline property. Its effect is not visible when there is only one row in the flexbox.

The align-content property has 6 different values flex-startflex-endcenterspace-aroundspace-between and stretch.

  1. flex-start: Aligns items to the start of the container packed together.
  2. flex-end: Aligns items to the end of the container packed together.
  3. center: Aligns items to the center of the container packed together.
  4. space-around: Aligns items equally distributed along each row packed together.
  5. space-between: Aligns items packed together between the start and end of the container. The first row starts from the top and the last row touches the bottom.
  6. stretch: Aligns items packed together and stretched along the cross axis of the container.
align content CSS
align content CSS

CSS align content example
1
2
3
4
5
6
7
8
9
10

Let's see an example for each value of the align-item property.

I. align-content flex-start

flex rows aligned to flex-start which forces flex-items to start from the top together in a group.

.container {  
  display: flex;
  align-content: flex-start;
  flex-wrap: wrap;
}
CSS
▶ Try it

Output:

1
2
3
4
5
6
7
8

II. align-content flex-end

flex rows aligned to flex-end which forces flex-items to start from the bottom together in a group.

.container {  
  display: flex;
  align-content: flex-end;
  flex-wrap: wrap;
}
CSS
▶ Try it

Output:

1
2
3
4
5
6
7
8

III. align-content center

flex rows align to the center of the container together in a group.

.container {  
  display: flex;
  align-content: center;
  flex-wrap: wrap;
}
CSS
▶ Try it

Output:

1
2
3
4
5
6
7
8

IV. align-content space-around

The space-around sets flex lines to align evenly in the container.

.container {  
  display: flex;
  align-content: space-around;
  flex-wrap: wrap;
}
CSS
▶ Try it

Output:

1
2
3
4
5
6
7
8

V. align-content space-between

flex rows aligned in space between the container's first row touching the top and the last row touching the bottom.

.container {  
  display: flex;
  align-content: space-between;
  flex-wrap: wrap;
}
CSS
▶ Try it

Output:

1
2
3
4
5
6
7
8

VI. align-content stretch

flex rows items are stretched along the cross axis.

.container {  
  display: flex;
  align-content: stretch;
  flex-wrap: wrap;
}
CSS
▶ Try it

Output:

1
2
3
4
5
6
7
8

Flexbox CSS that is applied on container's items (Child)

There are 6 different flexbox properties that are applied to the specific item of the flexbox container.

1. Flexbox order

The order CSS property of flexbox defines the order of an item in flexbox. Items of the container are sorted according to their order value in ascending order and then by their source code order.

The default value of the order is 0.

flexbox order
Flexbox order
CSS flexbox order example
1
2
3
4
5

Order accepts only Integers (both positive and negative), decimal values are not allowed

flexbox order example

#target1 {
  order: 0;
}

#target2 {
  order: 1;
}

#target3 {
  order: -1;
}

#target4 {
  order: 5;
}
CSS
▶ Try it

2. flex-grow CSS

The flex-grow CSS property defines a flex grow factor of any specific item's main size, where the main size is either height or width of the container depending on the flex-direction property.

The flex-grow property defines how the remaining space in the container will be assigned to the item, where the remaining space is the size of the container which remains after all items fit in.

The flex-grow value is always positive or 0, the negative value is not supported.

CSS flex grow example
1
2
3
4
5

flex grow example

Suppose you have 5 items of equal width 50px in a flex container with a width of 400px, and for simplicity suppose there is no margin between the items.

Remaining size: (400 - 50*5) = 150px

Now, if we set flex-grow: 1 to 3rd item then this 150px will be given to it. And its total width will become 50px + 150px = 200px.

If we set flex-grow: 0.5 to 3rd item then this 75px will be given to it (50%).

If we set flex-grow: 2 to 3rd item and flex-grow: 1 to 4rt item then 2/3 of remaining (100px) will be given to 3rd element and 1/3 of remaining size will be given to 4th element(50px).

flex grow CSS

#target1 {
  flex-grow: 2;
}

#target2 {
  flex-grow: 1;
}

#target3 {
  flex-grow: 0.5;
}
CSS
▶ Try it


3. flex-basis

The flex-basis CSS property is used to set the size of the flex item.

In case both flex-basis and width (or height) are defined for an element then flex-basis has priority.

#target1 {
  flex-basis: 150px;
}
CSS
▶ Try it
CSS flex basis example
1
2
3
4
5

4. flex-shrink

The flex-shrink CSS property is used to set the flex-shrink factor for a flex item.

It determines how much a flex item will shrink relative to the rest of the items in the container when the container is full.

#target1 {
  flex-shrink: 5;
}
CSS
▶ Try it

5. flex

This is a shorthand property for flex-growflex-basis and flex-shrink.

/* 1 value, unitless number: flex-grow */
flex: 1;

/* 1 value, width/height: flex-basis */
flex: 15px;
flex: 10%;

/* 2 values: flex-grow | flex-basis */
flex: 1 30px;

/* 2 values: flex-grow | flex-shrink */
flex: 2 2;

/* 3 values: flex-grow | flex-shrink | flex-basis */
flex: 2 2 10%;
CSS

6. align-self

The align-self property overwrites the align-items value for individual items. It aligns the item within the container on the Y-axis.

align item CSS

The align-self property has no effect on block-level items.

.container1 {
  display: flex;
  align-items: center;
}

#target1 {
  align-self: self-end;
}

.container2 {
  display: flex;
  align-items: flex-start;
}

#target2 {
  align-self: center;
}
CSS
▶ Try it
CSS align self example
1
2
3
4
5

Points to remember:

  1. CSS flexbox is a layout model which is used to position items in a container in 2D.
  2. To start with flexbox you have to define your parent container as a flexbox by using display: flex | inline-flex.
  3. Flexbox provides 6 different CSS properties for the parent element and 6 different CSS properties flexbox items.
  4. To practice CSS flexbox in a fun way you can visit flexbox froggy, which provides a game that uses flexbox knowledge to play, you can practice flexbox here by playing the game

CSS Media Queries - Make Responsive Websites


In this tutorial, you will learn about the CSS media query. What is it used for, how you can use it and how to make a responsive website using it.

What is a media query?

Media query is a technique introduced in CSS3 which let users define different CSS styles for different devices and different screen sizes.

It can modify the appearance and even behaviour of your webpage based on certain matched conditions.

It is useful when you want to design a webpage that auto-adjusts according to different devices like Desktop, laptop, pads, tablet, mobile etc.

media query CSS for all devices

Media query is mainly used to target a particular viewport range. It uses the @media rule with the condition to define a block of CSS which is applied to element when the condition is true. Here is an example we will discuss in detail later in this section.

/* applied on screensize of 768px and above */
@media screen and (min-width:768px) {
  .box {
    /* apply your style */
  }
}
CSS

Not only viewport width you can target a lot of things like screen resolution, device type, screen orientation, etc.


Media query syntax

Now you have understood what a media query is, let's look at its syntax with examples.

Media query has 4 different parts:

  1. At-rule (@media) - Media query starts with the @media ruleset itself.
  2. Logical operator (not, only, and) - Media query support logical operators like other programming languages like and, not, or (comma) and only.
  3. Media type (screen, printer, etc) - It defines the type of media we are targeting like print, screen, speech or all.
  4. Media-feature (width, max-width, height, etc) - Media feature target match features like width, height, aspect-ratio, orientation, etc.

media query syntax

A media query starts with the @media keyword followed by media-type and conditions separated by the logical operation.

@media not|only media-type and (mediafeature) {
  /* your CSS here... */
}
CSS

Here is a working example, in this example when the screen width gets greater than 768px than the background color of the webpage change to a light green color.

body {
  background-color: lightpink;
}

@media only screen and (min-width:768px) {
  body {
    background-color: lightgreen;
  }
}
CSS
▶ Try it

Media Query min width

The min-width media feature is used to set CSS properties for an element which works only when the minimum width of the media type (screen) is greater than the specified width.

In the example below, the background color and color of the webpage change when the screen width is greater than 500px.

Example 1

body {
  background-color: black;
  color: white;
}

/* effective when minimum width is greater than 500px */
@media only screen and (min-width: 500px) {
  body {
    background-color: lightpink;
    color: black;
  }
}
CSS
▶ Try it

Note: media queries must be last to define in style because defined styles are taken into consideration from top to down, if any media query is defined for any selector before defining normal CSS for that selector then the media query is ignored.

Here is another example where the column width increases to 100% when the viewport width gets smaller than 576px.

Example 2

.container {
  display: flex;
  flex-wrap: wrap;
  border: 1px solid black;
}

.col {
  width: 100%;
  text-align: center;
  outline: 1px solid gray;
  height: 30px;
  background-color: lightgreen;
}

@media only screen and (min-width:576px) {
  .col {
    width: 50%;
  }
}
CSS
▶ Try it

Media Query max width

The max-width in the media query is used to set CSS properties which work only when the maximum width of the media type (screen) is smaller than or equal to the specified width.

body {
  background-color: black;
  color: white;
}

/* effective when minimum width is greater than 500px */
@media only screen and (max-width: 500px) {
  body {
    background-color: lightpink;
    color: black;
  }
}
CSS
▶ Try it

Note: The operator only is optional operator modern browser don't need it.

/* this is also valid */
@media screen and (max-width: 500px) {
  body {
    background-color: lightpink;
    color: black;
  }
}
CSS

Hiding an element on mobile using media query

There are some situations when you want to hide certain elements of a webpage on a mobile device or divide with a specific viewport width.

You can use CSS display property and set it to none below breakpoint for mobile (here 320px is used).

div {
  background-color: tomato;
  color: white;
  padding: 10px;
  margin: 5px;
}

/* effective when window width is smaller than 320px */
@media screen and (max-width: 320px) {
  div {
    display: none;
  }
}
CSS
▶ Try it

Combining multiple media feature

Media query let you combine multiple media feature (condition) as well as multiple media types separated by logical operators.

Here is an example which target device width with viewport width between 500px to 800px. When device width is between 500px to 800px then background is lightgreen else white.

@media (min-width:500px) and (max-width:800px) {
  body {
    background-color: lightgreen;
  }
}
CSS
▶ Try it

Inverting a query meaning

The not logical operator inverts the entire meaning of the media query. It will invert only the specified media query it is applied to.

If there are other comma-separated media query then it is not applied to all.

The not is evaluated last in the query.

@media not screen and (print) { ... }
CSS

The above query is evaluated like this:

@media not (screen and (print)) { ... }
CSS

Not like this:

@media (not screen) and (print) { ... }
CSS

Here is another example:

@media not screen and (color), print and (min-width:500px) { ... }
CSS

The above query is evaluated like as follows:

@media (not screen and (color)), print and (min-width:500px) { ... }
CSS

Not like as follows:

@media (not screen and (color), print and (min-width:500px)) { ... }
CSS

Designing a responsive website using media query

The idea of the responsive website was generated from a media query.

Responsive websites are those websites that adjust elements size, alignment and orientation based on device width.

Let's design a webpage that is responsive to using media queries.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CSS - media query responsive webiste</title>
  <style>
    .container {
      display: flex;
      flex-direction: column;
    }

    .header {
      height: 80px;
      background-color: #16d5ef;
    }

    .left-sidebar {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 200px;
      margin-top: 10px;
      background-color: #ff7e47;
    }

    .sidebar-column {
      height: 30px;
      margin: 10px;
      background-color: white;
    }

    .main-element {
      padding: 0;
    }

    .main-column {
      background-color: #dfdfdf;
      height: 112px;
      margin-top: 10px;
    }

    .right-sidebar {
      height: 80px;
      margin-top: 10px;
      background-color: #2cda72;
    }

    @media (min-width:600px) {
      .left-sidebar {
        height: 50px;
        flex-direction: row;
      }

      .sidebar-column {
        width: calc(25% - 20px);
      }
    }

    @media (min-width:768px) {
      .container {
        flex-direction: row;
      }

      .left-sidebar {
        width: 20%;
        height: 600px;
        flex-direction: column;
      }

      .main-element {
        width: 65%;
        padding: 0 10px;
      }

      .sidebar-column {
        width: calc(100% - 20px);
        margin: 10px;
      }

      .right-sidebar {
        width: 15%;
        height: 600px;
      }
    }
  </style>
</head>

<body>
  <h2>Responsive website using media query</h2>
  <!-- Header -->
  <div class="header"></div>
  <div class="container">
    <!-- Left sidebar -->
    <div class="left-sidebar">
      <div class="sidebar-column"></div>
      <div class="sidebar-column"></div>
      <div class="sidebar-column"></div>
      <div class="sidebar-column"></div>
    </div>
    <!-- Main element -->
    <div class="main-element">
      <div class="main-column"></div>
      <div class="main-column"></div>
      <div class="main-column"></div>
      <div class="main-column"></div>
      <div class="main-column"></div>
    </div>
    <!-- Right sidebar -->
    <div class="right-sidebar"></div>
  </div>
</body>

</html>
HTML
▶ Try it

Output:

Responsive website using media query


Using Media Query in HTML

Media queries are not only applied in CSS but can be directly applied in HTML to load resources based on media type and media features.

Loading different external CSS based on viewport size

<link> element used for loading external CSS file to the webpage can use media attribute to load CSS file optionally.

<!-- Loaded to all users -->
<link rel="stylesheet" href="all.css" media="all">
<!-- Loaded to screens 320px or more wide -->
<link rel="stylesheet" href="small.css" media="(min-width: 320px)">
<!-- Loaded to screens 768px or more wide -->
<link rel="stylesheet" href="medium.css" media="(min-width: 768px)">
<!-- Loaded to print medias -->
<link rel="stylesheet" href="print.css" media="print">
HTML

You can see in the above code, you can load different CSS files based on device type or viewport size. It improves the page targeting for the different device as CSS loaded is more specific to the device.

But, this is not always the case when a small device like mobile visits the page then it loads the only file that satisfies the condition of a media query, while when you visit a device with a bigger viewport then it loads all CSS files for a matching device.

Not only in CSS files but you can use it load different <source> in <picture> element.

<picture>
  <!-- Load this image if the screen is at least 600px wide -->
  <source srcset="logo.webp" media="(min-width: 600px)">
  <!-- Load this image if the screen is at least 768px wide -->
  <source srcset="logo.webp" media="(min-width: 768px)">
  <!-- Load this image if nothing matches -->
  <img src="logo.webp" alt="A logo">
</picture>
HTML

Using Media Query in JavaScript

You can use media query in JavaScript also. You can create a media condition that targets a specific media type or media feature.

Use window.matchMedia() to define the condition.

// it is a media condition that target 768px or more wide viewport
const mediaQuery = window.matchMedia("(min-width: 768px)");
if (mediaQuery.matches) {
  console.log("Query matched!");
}
JavaScript

Conclusion

Nowadays it is necessary for your website to be responsive. And if you want to make responsive websites then media query is at the core. For responsive websites, the most famous choice is bootstrap framework, even bootstrap use media query at its code for responsiveness.


Points to remember:

  1. Media query can conditionally apply CSS properties to certain elements of the webpage when the device type of viewport dimension matches.
  2. It can load different resources only for a targeted device or targeted screen size. like in the <picture> element you can set multiple sources of an image that will load when a certain media condition satisfies.
  3. It will load an external CSS file that is attached for a media query even when the query is false in <link> element but will not apply its property to the page until the condition is true.
  4. Using window.matchMedia media query can also be used in JavaScript.














Comments