Author: Saim Khalid

  • Gradients

    CSS gradients allows to design custom colors for HTML elements by creating a smooth transition between two or more colors.

    What is CSS Gradient?

    • In CSS, gradient is a special type of user defined images that can be used for background or borders of element.
    • We can set a gradient to background property of any HTML elements using function gradient(type, color1, color2, color3);
    • Zooming a image gradient does not loose it’s quality as this are defined by browsers according to developers code.

    Table of Contents

    • Types of CSS Gradients
    • Linear Gradients
    • Radial Gradients
    • Conic Gradients
    • Gradients for Borders
    • Positioning Color Stops
    • Creating Hard Lines
    • Color Bands Using Gradients
    • Stacked Gradients
    • Related Functions

    Types of CSS Gradients

    CSS defines three types of gradients

    • Linear Gradient: Goes from left to right, up to down or diagonally.
    • Radial Gradient: Start from center to edges.
    • Conic Gradient: Revolve around a center point.

    Linear GradientRadial GradientConic Gradient

    Choose a gradient for background

    Linear Gradients

    The linear gradient creates a color band that flows in a single direction, i.e. from left-to-right, top-to-bottom, or at any angle.

    Syntax

    linear-gradient(direction, color1, color2, ...);/* Gradient from bottom right to top left */linear-gradient(to top left, color1, color2, ...);/* Gradient at an angle 45 degree */linear-gradient(45deg, red, yellow);

    The direction parameter specifies the angle or direction ( [to left | to right] || [to top | to bottom]) of the gradient.

    Example

    In order to create a basic linear gradient, you just need two colors, which are known as color stops. You must have minimum two, but can have more than two as well.

    Following example demonstrates this:

    <html><head><style>
    
      div {
         height: 70px;
         width: 100%;
      }
      .topBottom {
         background: linear-gradient(green, yellow);
      }
      .RightLeft{
         background: linear-gradient(to right, green, yellow);
      }
    </style></head><body><h1>Linear gradient</h1><h3>Top to Bottom ( Default )</h3><div class="topBottom"></div><h3>Right to left</h3><div class="RightLeft"></div></body></html>

    Radial Gradients

    radial gradient is a type of gradient that consists of colors radiating outward from a central point.

    In a radial gradient, the colors smoothly transition from one color at the center to another color at the outer edges in a circular or elliptical pattern.

    Syntax

    radial-gradient(shape size position, color1, color2..);
    • The shape parameter defines the shape of the gradient (circle or ellipse).
    • The size parameter specifies the size of the shape.
    • The position parameter sets the center of the gradient

    Example

    In order to create a basic radial gradient, you just need two colors. The center of the gradient is at 50% 50% mark, by default; where the gradient is elliptical matching with the aspect ratio of its box.

    Let us see an example:

    <html><head><style>
    
      div {
         height: 100px;
         width: 100%;
      }
      .gradient {
         background: radial-gradient(green, yellow);
      } 
      .center-gradient {
         background:
            radial-gradient(
               at 0% 50%,
               green 30px,
               yellow 60%,
               magenta 20%
            );
      }
    </style></head><body><h1>Radial gradient</h1><h3>Simple Radial Gradient</h3><div class="gradient"></div><h3>Center Positioned Radial Gradient</h3><div class="center-gradient"></div></body></html>

    Conic Gradients

    conic gradient, also known as a conical gradient or angular gradient, is a type of gradient in which colors are arranged in a circular or conical pattern, radiating out from a central point in a 360-degree arc.

    Syntax

    conic-gradient(from 'angle' at 'position','color-list')
    • position (optional): Specifies the position of the starting point of the gradient. It can be a percentage or a keyword like center.
    • angle (optional): Specifies the starting angle of the gradient in degrees.
    • color-list : Defines the colors and their positions in the gradient.

    Example

    In this example we will create a conic gradient pie chart with four different colors, then align gradient at different locations of diagram.

    <!DOCTYPE html><html lang="en"><head><style>
    
      div {
         height: 80px;
         width: 110px;
         border-radius: 50%; 
      }
      .gradient1{
         background: conic-gradient(
                        from 45deg at 50% 50%, 
                        red, yellow, green, 
                        blue, red);
      }
      .gradient2{
         background: conic-gradient(
                        from 45deg at 20% 40%, 
                        red, yellow, green, 
                        blue, red);
      }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;Conic Gradient Example&lt;/h1&gt;&lt;h3&gt;Align at center&lt;/h3&gt;&lt;div class="gradient1"&gt;&lt;/div&gt;&lt;h3&gt;Align at 20-40&lt;/h3&gt;&lt;div class="gradient2"&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Gradients for Borders

    The CSS gradients can be used to create fancy borders as well. You can use the gradients in wide variety to create effects in the border patterns.

    Syntax

    border-image:linear-gradient('color-list')

    You can also use radial and conical gradients for borders.

    Example

    Here is an example of use of gradients in creation of borders:

    <!DOCTYPE html><html lang="en"><head><style>
    
         .gradient-border {
            height: 200px;
            width: 200px;
            border: 10px solid;
            border-image: linear-gradient(
                              to right, 
                              red, yellow, 
                              green, blue) 1;
         }
      &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h2&gt;Gradient Border &lt;/h2&gt;&lt;div class="gradient-border"&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Positioning Color Stops

    Positioning color stops for gradient allows to control the point at which transition occur for a gradient.

    Syntax

    linear-gradient(to right, red 10%, pink 30%, blue 60%)
    • to right: Specifies the direction of gradient.
    • red 10%: Sets the red color to stop at 10% of the gradient
    • pink 30%: Sets the pink color to stop at 30% of the gradient.
    • blue 60%: Sets the blue color to stop at 60% of the gradient.

    Example

    <html><head><style>
    
      div {
         height: 100px;
         width: 100%;
      }
      .linear-position {
         background: linear-gradient(to right, 
                        blue 15px, magenta 33%, 
                        red 66%, yellow 60%, 
                        orange 100%);
      }
    </style></head><body><div class="linear-position"></div></body></html>

    Creating Hard Lines

    A hard line can be created in between two colors, such that no smooth transition can be seen. This effect can be achieved by carefully positioning color stops in CSS gradients. Check out following example

    Example

    In this example we will create hard line using gradient function.

    <html><head><style>
    
      div {
         height: 100px;
         width: 100px;
         display: inline-block;
         text-align: center;
         margin: 5px;
      }
      .linear-hard-line {
         background: linear-gradient(to top right, 
                           green 50%, orange 50%);
      }
    </style></head><body><div class="linear-hard-line"></div></body></html>

    Color Bands Using Gradients

    In order to create a striped effect, the second color stop for each color is set at the same location as the first color stop for the adjacent color.

    Syntax

    linear-gradient(to right, red 10%, 
    
               pink 10% 30%, 
               blue 60% 80%,
               yellow 80%);</pre>

    Example

    In this example will create a multi colored color band.

    <html><head><style>
    
      div {
         height: 100px;
         width: 100%;
      }
      .linear-gradient-stripes {
         background: linear-gradient(
                     to right,
                     green 20%,
                     lightgreen 20% 40%, 
                     orange 40% 60%,
                     yellow 60% 80%,
                     red 80%);
      }
    </style></head><body><div class="linear-gradient-stripes"></div></body></html>

    Stacked Gradients

    One gradient can be stacked over other gradients. Just make sure the gradient at the top should not be completely opaque, so that the gradients below it can be seen.

    Example

    Lets see an example of stacked gradients.

    <html><head><style>
    
      div {
         height: 200px;
         width: 100%;
      }
      .stacked-linear {
         background: 
            linear-gradient(90deg, green, yellow),
            linear-gradient(220deg, white 70.71%, black 38%),
            linear-gradient(217deg, orange, grey 70.71%);
      }
    </style></head><body><div class="stacked-linear"></div></body></html>

    Related Functions

    The following table lists all the functions related to CSS gradients:

    Gradient TypeDescriptionExample
    linear-gradient()Type of gradient in which colors transition in a straight line from one point to another.Try It
    radial-gradient()Type of gradient that consists of colors radiating outward from a central point.Try It
    conic-gradient()Type of gradient in which colors are arranged in a circular or conical pattern.Try It
    repeating-linear-gradient()Allows you to create a linear gradient pattern that repeats in a specified direction.Try It
    repeating-radial-gradient()Allows you to create a repeating radial gradient pattern.Try It
    repeating-conic-gradient()Allows you to create a repeating conic gradient pattern.Try It
  • Colors

    CSS uses color values to specify a color. Typically, these are used to set a color either for the foreground of an element (i.e. its text) or else for the background of the element. They can also be used to affect the color of borders and other decorative effects.

    You can specify your color values in various formats. Following table lists all the possible formats −

    FormatSyntaxDescriptionExample
    Keyword<property>: <colorname>CSS has a set of predefined color names that you can use directly.red, blue, green, yellow, black, white, etc.
    Hexadecimal Code#RRGGBBStarts with a hash (#) followed by six hexadecimal digits.#FF0000 – red
    Short Hexadecimal Code#RGBShorter version of hexadecimal format where each of the RGB components is represented by a single digit, and the value is duplicated.#F00 – red
    RGBrgb(red,green,blue)Colors can be defined using the rgb() function, which takes three parameters representing the red, green, and blue values.rgb(0, 0, 255) – blue
    RGBArgba()Similar to RGB, with an additional parameter for the alpha (transparency) value. 0 (fully transparent) and 1 (fully opaque)rgba(0,0,255,0.5) – translucent blue
    HSLhsl()Colors can be defined using the rgb() function which stands for Hue (0 to 360 degree), Saturation (%), and Lightness (%).hsl(120, 100%, 50%) – pure green
    HSLAhsla()Similar to HSL, with an additional parameter for the alpha (transparency) value.hsl(120, 100%, 50%, 0.5) – translucent green
    currentcolor KeywordcurrentcolorIt refers to the value of the color property of the element.color: red; /* Red text color */ border: 10px solid currentcolor; /* Red border color */
    System coloras per OS or browserCSS allows usage of system colors defined by the user’s OS or browser.ButtonText, Window, WindowText

    These formats are explained in more detail in the following sections −

    CSS Colors – Keyword

    CSS supports the color names to be directly passed to the property background-color and color. 140 standard color names are supported by CSS.

    Few of the examples are listed in the table below:

    ColorColor Name
     Black
     Red
     Blue
     Green
     Aquamarine

    Here is an example:

    Open Compiler

    <html><head><style>
       #colorkeyword{
    
      background-color: aqua;
      padding: 10px;
    } </style></head><body><h3>Color Keyword - example</h3><p>As the keyword passed is aqua, the background will appear as aqua colored..</p><div id="colorkeyword">
      This div element has a colored background based on the color keyword passed, i.e aqua.
    </div></body></html>

    CSS Colors – Hexadecimal Codes

    A hexadecimal is a 6 digit representation of a color. The first two digits(RR) represent a red value, the next two are a green value(GG), and the last are the blue value(BB).

    A hexadecimal value can be taken from any graphics software like Adobe Photoshop, Jasc Paintshop Pro, or even using Advanced Paint Brush.

    Each hexadecimal code will be preceded by a pound or hash sign ‘#’. Following are the examples of hexadecimal notation.

    Note: To specify the hexadecimal codes, you can use upper case or lower case letters.

    ColorColor Hexadecimal Code
     #000000
     #FF0000
     #00FF00
     #0000FF
     #FFFF00
     #00FFFF
     #FF00FF
     #C0C0C0
     #FFFFFF

    Here is an example:

    Open Compiler

    <html><head><style>
       #hexcode {
    
      background-color: #00ff00;
      padding: 10px;
    } </style></head><body><h3>Hexadecimal code - example</h3><p>As the hexadecimal code is #00ff00 the background will appear green.</p><div id="hexcode">
         This div element has a green background.
      &lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Colors - Short Hexadecimal Codes

    This is a shorter form of the six-digit notation. In this format, each digit is replicated to arrive at an equivalent six-digit value. For example: #6A7 becomes #66AA77.

    A hexadecimal value can be taken from any graphics software like Adobe Photoshop, Jasc Paintshop Pro, or even using Advanced Paint Brush.

    Each short hexadecimal code will be preceded by a pound or hash sign '#'. Following are the examples of short hexadecimal notation.

    Note: To specify the hexadecimal codes, you can use upper case or lower case letters.

    ColorShort Hexadecimal Code
     #000
     #F00
     #0F0
     #0FF
     #FF0
     #0FF
     #F0F
     #FFF

    Here is an example:

    Open Compiler

    <html><head><style>
       #shorthex {
    
      background-color: #00f;
      padding: 10px;
    } </style></head><body><h3>Short Hexadecimal code - example</h3><p>As the short hexadecimal code is #00f the background will appear blue.</p><div id="shorthex">
         This div element has a blue background.
      &lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Colors - RGB Values

    • This color value is specified using the rgb( ) property.
    • It takes three values, one each for red, green, and blue.
    • The value can be an integer between 0 and 255 or a percentage.

    NOTE: All the browsers does not support rgb() property of color so it is recommended not to use it.

    Following is the example to show few colors using RGB values.

    ColorColor RGB
     rgb(0,0,0)
     rgb(255,0,0)
     rgb(0,255,0)
     rgb(0,0,255)
     rgb(255,255,0)
     rgb(0,255,255)
     rgb(255,0,255)
     rgb(192,192,192)
     rgb(255,255,255)

    Here is an example:

    Open Compiler

    <html><head><style>
       #rgbvalue {
    
      background-color: rgb(255,0,255);
      padding: 10px;
    } </style></head><body><h3>RGB - example</h3><p>As the rgb(255,0,255) is set the background will appear accordingly.</p><div id="rgbvalue">
      This div element has a colored background based on the rgb values.
    </div></body></html>

    CSS Colors - RGBA Values

    • This color value is specified using the rgba( ) property.
    • It takes four values, one each for red, green, and blue and the last value as the alpha (transparency) value.
    • The alpha value can be any value between 0 and 1.

    NOTE: All the browsers do not support rgba() property of color so it is not recommended.

    Following is the example to show few colors using RGBA values.

    ColorColor RGBA
     rgba(0,0,0,0)
     rgba(255,0,0,0.2)
     rgba(0,255,0,0.3)
     rgba(0,0,255,0.5)
     rgba(255,255,0,0.7)
     rgba(0,255,255,0.1)
     rgba(255,0,255,1)
     rgba(192,192,192,0.4)
     rgba(255,255,255,1)

    Here is an example:

    Open Compiler

    <html><head><style>
       #rgbavalue {
    
      background-color: rgba(255,0,255,0.2);
      padding: 10px;
    } </style></head><body><h3>RGBA - example</h3><p>As the rgba(255,0,255,0.2) is set the background will appear with transparency value of 0.2.</p><div id="rgbavalue">
      This div element has a colored background based on the rgba values.
    </div></body></html>

    CSS Colors - HSL Values

    • This color value is specified using the hsl() function.
    • HSL stands for hue, saturation and lightness.
    • Hue is represented in degrees (0-360), saturation and lightness are represented as percentages (0% - 100%).

    Following is the example to show few colors using HSL property.

    ColorColor HSL
     hsl(0,0%,50%)
     hsl(255,80%,70%)
     hsl(290,100%,60%)
     hsl(360,70%,20%)
     hsl(89,80%,67%)

    Here is an example:

    <html><head><style>
       #hslvalue {
    
      background-color: hsl(355,70%,50%);
      padding: 10px;
    } </style></head><body><h3>HSL - example</h3><p>As the hsl(355,70%,50%) is set the background will appear based on the hsl values passed.</p><div id="hslvalue">
      This div element has a colored background based on the hsl values hsl(355,70%,50%).
    </div></body></html>

    CSS Colors - HSLA Values

    • This color value is specified using the hsl() function.
    • HSLA stands for hue, saturation, lightness and alpha.
    • It takes four values, first for hue, second for saturation, third for lightness and fourth is the alpha (transparency) value.
    • Hue is represented in degrees (0-360), saturation and lightness are represented as percentages (0% - 100%), and alpha value can be in between 0 and 1.

    Following is the example to show few colors using HSLA property.

    ColorColor HSLA
     hsla(0,0%,50%,0.5)
     hsla(255,80%,70%,1)
     hsla(290,100%,60%,0.2)
     hsla(360,70%,20%,0.4)
     hsla(89,80%,67%,0.9)

    Here is an example:

    <html><head><style>
       #hslavalue {
    
      background-color: hsla(355,70%,50%,0.4);
      padding: 10px;
    } </style></head><body><h3>HSLA - example</h3><p>As the hsla(355,70%,50%,0.4) is set the background will appear based on the hsla values passed, with high transparency.</p><div id="hslavalue">
      This div element has a colored background based on the hsl values hsla(355,70%,50%,0.4).
    </div></body></html>

    CSS Colors - currentcolor keyword

    The currentcolor keyword signifies the value of the color property of an element. It can be passed to any other styling property using the keyword currentcolor.

    Here is an example:

    <html><head><style>
       #currcolor {
    
      color: red;
      border: 5px solid currentcolor;
    } </style></head><body><h2>The currentcolor Keyword</h2><p>As the currentcolor keyword is used for border after color property is set as red, the border will also appear red.</p><div id="currcolor">
      This div element has a red text color and a red border.
    </div></body></html>

    CSS Colors - Building Color Codes

    You can build millions of color codes using our Color Code Builder. Check the HTML Color Code Builder.

    To use this tool, you would need a Java Enabled Browser.

    CSS Colors - Browser Safe Colors

    Here is the list of 216 colors which are supposed to be most safe and computer independent colors. These colors vary from hexa code 000000 to FFFFFF. These colors are safe to use because they ensure that all computers would display the colors correctly when running a 256 color palette −

    0000000000330000660000990000CC0000FF
    0033000033330033660033990033CC0033FF
    0066000066330066660066990066CC0066FF
    0099000099330099660099990099CC0099FF
    00CC0000CC3300CC6600CC9900CCCC00CCFF
    00FF0000FF3300FF6600FF9900FFCC00FFFF
    3300003300333300663300993300CC3300FF
    3333003333333333663333993333CC3333FF
    3366003366333366663366993366CC3366FF
    3399003399333399663399993399CC3399FF
    33CC0033CC3333CC6633CC9933CCCC33CCFF
    33FF0033FF3333FF6633FF9933FFCC33FFFF
    6600006600336600666600996600CC6600FF
    6633006633336633666633996633CC6633FF
    6666006666336666666666996666CC6666FF
    6699006699336699666699996699CC6699FF
    66CC0066CC3366CC6666CC9966CCCC66CCFF
    66FF0066FF3366FF6666FF9966FFCC66FFFF
    9900009900339900669900999900CC9900FF
    9933009933339933669933999933CC9933FF
    9966009966339966669966999966CC9966FF
    9999009999339999669999999999CC9999FF
    99CC0099CC3399CC6699CC9999CCCC99CCFF
    99FF0099FF3399FF6699FF9999FFCC99FFFF
    CC0000CC0033CC0066CC0099CC00CCCC00FF
    CC3300CC3333CC3366CC3399CC33CCCC33FF
    CC6600CC6633CC6666CC6699CC66CCCC66FF
    CC9900CC9933CC9966CC9999CC99CCCC99FF
    CCCC00CCCC33CCCC66CCCC99CCCCCCCCCCFF
    CCFF00CCFF33CCFF66CCFF99CCFFCCCCFFFF
    FF0000FF0033FF0066FF0099FF00CCFF00FF
    FF3300FF3333FF3366FF3399FF33CCFF33FF
    FF6600FF6633FF6666FF6699FF66CCFF66FF
    FF9900FF9933FF9966FF9999FF99CCFF99FF
    FFCC00FFCC33FFCC66FFCC99FFCCCCFFCCFF
    FFFF00FFFF33FFFF66FFFF99FFFFCCFFFFFF

    CSS Colors - Related Properties

    All the properties related to color are listed in the table below:

    PropertyDescription
    opacitySets the transparency level of an element.
    hueRepresents the hue angle of an element.
    colorSets the foreground of an element's text and text decoration.
    background-colorSets the color of the background.
    border-colorSets the color of the border of an element.
    box-shadowAdds a shadow effect around an element.
    outline-colorSets the color of the outline around an element.
    text-shadowAdds shadow to the text of an element.
  • Multiple Backgrounds

    In CSS, you can use multiple background images for an element. First background should be layered on top, and the last background should be layered behind. Only the last background can have a background color.

    Syntax

    .multibackgrounds {
       background:
    
      background1,
      background2,
      /* , */ backgroundN;
    }

    You can use shorthand and individual background properties, excluding background-color.

    The following background properties can be provided as a list, one for each background: backgroundbackground-attachmentbackground-clipbackground-imagebackground-originbackground-positionbackground-repeatbackground-size.

    CSS Multiple Backgrounds – Using background-image property

    The following example demonstrates adding two background images using background-image property, where the first image is stacked on top and the second is behind it −

    <html><head><style>
       .multibackgrounds {
    
      background-image: url(images/logo.png), url(images/see.jpg);
      background-position: left top, right top;
      background-repeat: no-repeat, repeat;
      padding: 70px;
    } </style></head><body><div class="multibackgrounds"><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p></div></body></html>

    CSS Multiple Backgrounds – Using background-size Property

    The following example demonstrates the use of multiple background images of different sizes using background-size property. The first image’s size is 150px, and the second image’s size is 300px −

    <html><head><style>
       .multibackgrounds{
    
      background-image: url(images/logo.png), url(images/see.jpg);
      background-position: left top, right top;
      background-repeat: no-repeat, repeat;
      padding: 70px;
    } .multibackgrounds-size {
      background-image: url(images/logo.png), url(images/see.jpg);
      background-position: left top, right top;
      background-repeat: no-repeat, repeat;
      background-size: 150px, 300px;
      padding: 70px;
    } </style></head><body><h3>Without Sizing</h3><div class="multibackgrounds"><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p></div><br><h3>With Sizing</h3><div class="multibackgrounds-size"><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p></div></body></html>

    CSS Multiple Backgrounds – Using background Property

    The following example demonstrates addition of three background images using the shorthand property background −

    <html><head><style>
       .multibackgrounds-size {
    
      background: url(images/logo.png),  url(images/pink-flower.jpg), url(images/see.jpg);
      background-position: left top, center, right top;
      background-repeat: no-repeat, no-repeat, no-repeat;
      background-size: 150px, 100px, 550px;
      padding: 70px;
      color: yellow;
    } </style></head><body><div class="multibackgrounds-size"><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p></div></body></html>

    CSS Multiple Backgrounds – Full Size Image

    The following example demonstrates full sized background image, set using background-size: cover property −

    <html><head><style> 
       html { 
    
      background: url(images/red-flower.jpg) no-repeat center fixed; 
      background-size: cover;
      color: yellow; 
    } </style></head><body><h1>Red Flower Image</h1><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p></body></html>

    CSS Multiple Backgrounds – Hero Image

    The following example demonstrates the setting of a hero image, refers to a large image with text using different background properties on <div> −

    <html><head><style>
       .background-img {
    
      background: url(images/see.jpg) no-repeat center; 
      background-size: cover;
      height: 300px;
      position: relative;
    } .background-text {
      text-align: center;
      position: absolute;
      top: 40%;
      left: 50%;
      transform: translate(-50%, -50%);
      color: red;
    } button {
         background-color: yellow;
         padding: 10px;
    } </style></head><body><div class="background-img"><div class="background-text"><h1>See Image</h1><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.</p><button>Click Me</button></div></div></body></html>

    CSS Multiple Backgrounds – Using background-origin Property

    The following example demonstrates how the background image is positioned within a box using background-origin property −

    <html><head><style>
       div {
    
      width: 200px;
      height: 150px;
      border: 7px solid blue;
      padding: 30px;
      background: url(images/pink-flower.jpg);
      background-repeat: no-repeat;
      margin: 10px;
    } P {
      color: yellow;
    } h3 {
      color: red;
    } .box1 {
      background-origin: padding-box;
    } .box2 {
      background-origin: border-box;
    } .box3 {
      background-origin: content-box;
    } </style></head><body><div class="box1"><h3>background-origin: padding-box</h3><p>Background image is positioned relative to the padding box.</p></div><div class="box2"><h3>background-origin: border-box</h3><p>Background image is positioned relative to the border box.</p></div><div class="box3"><h3>background-origin: content-box</h3><p>Background image is positioned relative to the content box.</p></div></body></html>

    CSS Multiple Backgrounds – Using background-clip Property

    The following example demonstrates how the background image should be displayed within box using background-clip property −

    <html><head><style>  
       p {
    
      width: 200px;
      height: 150px;
      border: 8px solid blue;
      margin: 10px;
      padding: 30px;
      color: yellow;
      background: url(images/pink-flower.jpg);
    } .box1 {
      background-clip: border-box;
    } .box2 {
      background-clip: padding-box;
    } .box3 {
      background-clip: content-box;
    } </style></head><body><p class="box1">Background image is applied to the entire element.</p><p class="box2">Background image is applied to the padding area.</p><p class="box3">Background image is applied only to the content area.</p></body></html>

    CSS Multiple Backgrounds – Related Properties

    All the properties related to background are listed in the table below:

    PropertiesDescription
    backgroundShorthand for background related properties.
    background-attachmentSpecifies the position of the background relative to the viewport, either fixed or scrollable.
    background-clipControls how far a background image extends beyond the element’s padding or content box.
    background-imageSets one or more background image(s) on an element.
    background-originSets the origin of the background.
    background-positionSets the initial position of each image in a background.
    background-repeatControls the repetition of an image in the background.
    background-sizeControls the size of the background image.
  • Border Images

    CSS border-images properties are used to create custom borders by setting image as border around any element.

    The border-image property takes the image and slices it into nine sections(3×3). It then places the corners at the corner of the border, and the edges are repeated or stretched as you specify. Middle part of image will be ignored.

    Border Image

    Table of Contents

    • Example of Image as Border
    • CSS Border Image Source
    • CSS Border Image Slice
    • CSS Border Image Width
    • CSS Border Image Outset
    • CSS Border Image Repeat
    • Border Image Shorthand
    • CSS Gradient as Border Images
    • Border Image All Properties

    Example of Image as Border

    The following code shows a basic example of how to set image as border.

    Example

    <!DOCTYPE html><html><head><style>
    
        div{
            background-color: #f0f0f0;
            border: 20px solid transparent;
            border-image: url(/css/images/border.png) 40;
            padding: 20px;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div&gt;&lt;p&gt;
            This is an example of setting a 
            border image using CSS
        &lt;/p&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Border Image Source

    The CSS border-image-source property specifies the source (url) of an image to be passed as a border to an element.

    Example

    <!DOCTYPE html><html><head><style>
    
        div{
            background-color: #f0f0f0;
            border: 20px solid transparent;
            border-image-source: url(/css/images/border.png);
            padding: 20px;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div&gt;&lt;p&gt;
            This is an example of setting border image using 
            border image source.
        &lt;/p&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Border Image Slice

    The border-image-slice property defines how the image is sliced into regions, which are then used to draw the borders.

    The following diagram demonstrates how image is sliced to make border. The image is divided into 9 sections: four corners, four edges, and the center.

    border-image-slice structure

    The value in the 'border-image-slice' property specifies how far inward from the edges of the image the slicing should occur. It essentially defines the size of the areas that will be used to create the border.

    The offset for border-image-slice can be provided in terms of percentage or length units but percentages are highly recommended.

    Example

    <!DOCTYPE html><html><head><style>
    
        div{
            background-color: #f0f0f0;
            border: 20px solid transparent;
            border-image-source: url(/css/images/scenery2.jpg);
            border-image-slice: 25%;
            padding: 15px;
            width: 50%
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div&gt;&lt;p&gt;
            See how border is set for this div...
        &lt;/p&gt;&lt;/div&gt;&lt;p&gt; Here is full image for your reference: &lt;/p&gt;&lt;img src="/css/images/scenery2.jpg" height="160px"&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Border Image Width

    The border-image-width property is used to specify the width of the image to be set as a border.

    Example

    <!DOCTYPE html><html><head><style>
    
        div{
            background-color: #f0f0f0;
            border: 20px solid transparent;
            border-image-source: url(/css/images/border.png);
            border-image-width: 5px;
            border-image-slice: 25%;
            padding: 5px;
            margin: 20px;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div&gt;
        border-image-width: 5px;
    &lt;/div&gt;&lt;div style="border-image-width: 10px;"&gt;
        border-image-width: 10px;
    &lt;/div&gt;&lt;div style="border-image-width: 15px;"&gt;
        border-image-width: 15px;
    &lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Border Image Outset

    The border-image-outset property is used to specify gap between element and border-image. This property pushes the border image outside, beyond the border box.

    Example

    <!DOCTYPE html><html><head><style>
    
        div{
            background-color: grey;
            border: 20px solid transparent;
            border-image-source: url(/css/images/border.png);
            border-image-width: 10px;
            border-image-slice: 25%;
            border-image-outset: 0px;
            padding: 5px;
            width: 80%;
            margin: 10px 15px 60px;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div&gt;
        border-image-outset: 0px;
    &lt;/div&gt;&lt;div style="border-image-outset: 20px;"&gt;
        border-image-outset: 20px;
    &lt;/div&gt;&lt;div style="border-image-outset: 25px;"&gt;
        border-image-outset: 25px;   
    &lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Border Image Repeat

    The border-image-repeat property in used to repeating and stretching nature of image around border. By default the border image gets stretched along the sides.

    The value repeat for this property, repeats the image specified along the sides of the border until the whole length and width got filled.

    It can also take the value as round, apart from stretch and repeat.

    Example

    <!DOCTYPE html><html><head><style>
    
        div{
            background-color: #f0f0f0;
            border: 20px solid transparent;
            border-image-source: url(/css/images/border.png);
            border-image-slice: 25%;
            border-image-repeat: repeat;
            padding: 20px;
            width: 80%;
            margin: 10px 15px 60px;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div&gt;
        Border Image Repeat
    &lt;/div&gt;&lt;div style="border-image-repeat: stretch;"&gt;
        Border Image Stretch
    &lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Border Image Shorthand Property

    The border-image shorthand property allows you to set all the properties related to border images in one declaration.

    border-image: image-source | image-slice | image-repeat;

    Following example shows how to use this property.

    Example

    <!DOCTYPE html><html><head><style>
    
        div{
            background-color: #f0f0f0;
            border: 20px solid transparent;
            border-image: url('/css/images/border.png') 30 round;
            padding: 20px;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div&gt;&lt;p&gt;
            This is an example of border shorthand property....
        &lt;/p&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Gradient as Border Images

    CSS gradients can also be used to set the border of an element. There are three types of gradients supported: linear, radial and conic.

    Following example shows how to use this property.

    Example

    <!DOCTYPE html><html><head><style>
    
        div{
            background-color: #f0f0f0;
            border: 20px solid transparent;
            border-image: linear-gradient(45deg, green, yellow) 1;
            padding: 20px;
            margin: 20px;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div&gt;
        Border image linear gradient.
    &lt;/div&gt;&lt;div style="border-image: radial-gradient(green, yellow) 1;"&gt;
        Border image radial gradient.
    &lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Border Images All Properties

    All the properties related to border-images are listed in the table below:

    PropertyDescriptionExample
    border-imageA shorthand property for setting border image.Try It
    border-image-outsetSets the image outset i.e how much the border image area extends beyond the border box.Try It
    border-image-repeatDetermines whether the border image should be repeated, rounded, spaced or stretched.Try It
    border-image-sourceSets the source/path of an image to be passed as a border to an element.Try It
    border-image-sliceShows how to slice up an image in a border.Try It
    border-image-widthSets the width of the image to be set as a border.Try It

  • Rounded Corners

    CSS rounded corners are created using the border-radius property. This property allows you to specify the radius of the corners of an element’s outer border edge.

    Possible Values

    • <length>: Size of circle radius is denoted, using length values. Negative values are not valid.
    • <percentage>: Size of circle radius is denoted, using percentage values.
      • Horizontal axis percentage is referred to the width of the box.
      • Vertical axis percentage is referred to the height of the box.
      • Negative values are not valid.

    Applies to

    All the HTML elements, except for table and inline-table elements with border-collapse set to collapse. Applies to ::first-letter.

    DOM Syntax

    object.style.borderRadius = "length";
    

    The following diagram demonstrates the different border-radius corners for reference:

    border-radius

    The following table shows the possible values for rounded corners as follows −

    ValueDescription
    radiusAll CornerIs a <length> or a <percentage> that sets the radius for all four corners of the element. It is used only in the one-value syntax.
    top-left and bottom-rightTop Left Bottom RightIs a <length> or a <percentage> that sets the radius for the top-left and bottom-right corners of the element. It is used only in the two-value syntax.
    top-right and bottom-leftTop Right Bottom LeftIs a <length> or a <percentage> that sets the radius for the top-right and bottom-left corners of the element. It is used only in the two- and three-value syntaxes.
    top-leftTop LeftIs a <length> or a <percentage> that sets the radius for the top-left corner of the element. It is used on three and four value syntaxes.
    top-rightTop RightIs a <length> or a <percentage> that sets the radius for the top-right corners of the element. It is used only in the four-value syntax.
    bottom-rightBottom RightIs a <length> or a <percentage> that sets the radius for the bottom-right corners of the element. It is used only in the three and four-value syntaxes.
    bottom-leftBottom LeftIs a <length> or a <percentage> that sets the radius for the bottom-left corners of the element. It is used only in the four-value syntax.

    Individual border radius properties, such as border-top-left-radius, cannot inherit from their parent element. Instead, you must use the individual longhand properties to set the border radius of each corner.

    CSS Border Radius – Length Value

    The following example demostrates how to use the border-radius property to create rounded corners for all four corners of a box −

    <html><head><style>
       .rounded-box {
    
      width: 200px;
      height: 100px;
      background-color: pink;
      line-height: 100px;
      border-radius: 20px;
    } </style></head><body><div class="rounded-box">
      This is a rounded corner box.
    </div></body></html>

    You can use the border-radius property to create rounded corners on box, borders, and images.

    Here is an example −

    <html><head><style>
       .rounded-box {
    
      width: 200px;
      height: 100px;
      background-color: pink;
      border-radius: 20px;
      margin-bottom: 10px;
    } .border-box {
      width: 200px;
      height: 100px;
      border-radius: 2em;
      border: 3px solid green; 
      margin-bottom: 20px;   
    } .img-border-radius {
      background-image: url(images/tree.jpg);
      background-size: 100% 100%;
      border-radius: 20%;
      width: 200px;
      height: 150px;
    } </style></head><body><div class="rounded-box">
      This is a rounded corner box.
    </div><div class="border-box">
      This is a rounded corner box.
    </div><div class="img-border-radius">
      This is a rounded corner image.
    </div></body></html>

    You can use the border-radius property to create different rounded corner styles on an element.

    Here is an example −

    <html><head><style>
       .rounded-box {
    
      width: 200px;
      height: 100px;
      background-color: pink;
      margin: 10px;
      padding: 5px;
    } .rounded-box.tl {
      border-radius: 30px 0 0 0;
    } .rounded-bo x.tr {
      border-radius: 0 2em 0 0;
    } .rounded-box.bl {
      border-radius: 0 0 0 15%;
    } .rounded-box.br {
      border-radius: 0 0 30px 0;
    } .rounded-box.tl-br {
      border-radius:  2em 0 2em 0;
    } .rounded-box.tr-bl {
      border-radius: 0 15% 0 15%;
    } </style></head><body><div class="rounded-box tl">
      top-left rounded corner.
    </div><div class="rounded-box tr">
      top-right rounded corner.
    </div><div class="rounded-box bl">
      bottom-left rounded corner.
    </div><div class="rounded-box br">
      bottom-right rounded corner.
    </div><div class="rounded-box tl-br">
      top-left and bottom-right rounded corners.
    </div><div class="rounded-box tr-bl">
      top-right and bottom-left rounded corners.
    </div></body></html>

    CSS Rounded Corner Images

    You can use the border-radius property to create different rounded corner styles on elements.

    Here is an example −

    <html><head><style>
       img {
    
      width: 200px;
      height: 100px;
      margin: 10px;
    } .top-left {
      border-radius: 30px 0 0 0;
    } .top-right {
      border-radius: 0 2em 0 0;
    } .bottom-left {
      border-radius: 0 0 0 15%;
    } .bottom-right {
      border-radius: 0 0 30px 0;
    } .tl-br {
      border-radius:  2em 0 2em 0;
    } .tr-bl {
      border-radius: 0 15% 0 15%;
    } </style></head><body><h4>top-left rounded corner.</h4><img class="top-left" src="images/tree.jpg" /><h4>top-right rounded corner.</h4><img class="top-right" src="images/tree.jpg" /><h4> bottom-left rounded corner.</h4><img class="bottom-left" src="images/tree.jpg" /><h4>bottom-right rounded corner.</h4><img class="bottom-right" src="images/tree.jpg" /><h4>top-left and bottom-right rounded corners.</h4><img class="tl-br" src="images/tree.jpg" /><h4>top-right and bottom-left rounded corners.</h4><img class="tr-bl" src="images/tree.jpg" /></body></html>

    We can create a circle and an ellipse using the CSS border-radius property.

    Here is an example −

    <html><head><style>
       .rounded-circle {
    
      width: 100px;
      height: 100px;
      background-color: pink;
      text-align: center;
      border-radius: 50%;
    } .rounded-ellipse {
      width: 200px;
      height: 100px;
      background-color: pink;
      text-align: center;
      border-radius: 50%;
    } </style></head><body><div class="rounded-circle">
      circle
    </div><div class="rounded-ellipse">
      ellipse
    </div></body></html>

    CSS border-radius – Related Properties

    Following is the list of CSS properties related to border-radius:

    propertyvalue
    border-top-left-radiusSets the roundness of the top-left corner of an element’s border.
    border-top-right-radiusSets the roundness of the top-right corner of an element’s border.
    border-bottom-right-radiusSets the roundness of the bottom-right corner of an element’s border.
    border-bottom-left-radiusSets the roundness of the bottom-left corner of an element’s border.
    border-start-start-radiusSets the roundness of the block-start and inline-start corner of an element’s border.
    border-start-end-radiusSets the roundness of the block-start and inline-end corner of an element’s border.
    border-end-start-radiusSets the roundness of the block-end and inline-start corner of an element’s border.
    border-end-end-radiusSets the roundness of the block-end and inline-end corner of an element’s border.
  • Data Types

    CSS data types define the types of values that can be used for various CSS properties. Each CSS property expects a specific type of value, and understanding these data types is essential for properly styling and formatting web content.

    The types listed below are the most common, however it is not a complete list of all types defined in any CSS specification.

    Syntax

    selector {
       property: <unit-data-type>;
    }      
    

    CSS syntax uses a keyword between the inequality signs “<” and “>” to indicate data types.

    Textual Data Types

    These types include keywords, identifiers, strings, and URLs.

    Pre-defined Keywords

    Represents a predefined keyword that is specific to the property it’s used with (e.g., auto, inherit, none).

    CSS-wide keywords

    The table given below lists all the CSS-wide keywords:

    PropertyDescription
    <custom-ident>A user-defined identifier, such as a name given with the grid-area property.
    <dashed-ident>Using CSS Custom Properties, a <custom-ident> begin with two dashes.
    <string>A string that has been quoted, such as the value for the content property.
    url()A reference to a resource, such the background-image value.

    Numeric Data Types

    These data types represent quantities, indexes, and positions. The following table lists all the numeric data types:

    PropertyDescription
    <integer>One or more decimal units (09).
    <number>Real numbers may include a fractional component, such as 1 or 1.54.
    <dimension>A numerical value that includes a unit, such as 23px or 15em.
    <percentage>A numerical value that includes a percentage symbol, such as 15%.
    <ratio>A ratio is represented as <number> / <number>.
    <flex>CSS Grid Layout introduces a flexible length, represented by a <number> with the fr unit attached for grid track sizing.

    Quantities

    Distance and other quantities are defined using these types. The following table lists all the quantities:

    PropertyDescription
    <length>Lengths are a dimension that refers to distances.
    <angle>Angles are represented as a <dimension> with deg, grad, rad, or turn units, and used in properties such as linear-gradient().
    <time>Duration units are represented as a <dimension> with a s or ms unit.
    <resolution>This is a <dimension> with the unit identifier dpi, dpcm, dppx, or x.

    Combinations of Types

    CSS properties that accept both a dimension and a percentage value fall in this category. The percentage value will be converted to a quantity relative to the allowable dimension. Properties that take both a percentage and a dimension will use one of the following types:

    PropertyDescription
    <length-percentage>A type that can take a a length or a percentage value.
    <angle-percentage>A type that can take a a angle or a percentage value.
    <time-percentage>A type that can take a a time or a percentage value.

    Color

    Color related properties define the <color> data type and additional types related to colors.

    The following table lists all the color related data types:

    PropertyDescription
    <color>A color represented as a keyword or a numerical value.
    <color-interpolation-method>Determines the color space used when creating a transition between different <color> values.
    <hex-color>Describes the hexadecimal color syntax of an sRGB color using the primary color components (red, green, blue) denoted as hexadecimal numbers, along with its transparency.
    <system-color>Commonly linked to the default color selections for different components on a webpage.
    <alpha-value>Represents the transparency of a color. The value can be either a <number> (0 is fully transparent, 1 is fully opaque) or a <percentage> (0 is fully transparent, 100% is fully opaque).
    <hue>Define the <angle> of the color wheel for the <absolute-color-functions> component using units such as, deg, grad, rad, turn, or a unitless number (interpreted as deg).
    <hue-interpolation-method>Determines the algorithm that is used for interpolation between hue values. This method specifies how to find a midpoint between two hue values based on a color wheel. It is a component of the <color-interpolation-method> data type.
    <named-color>Specified as a <ident> in syntax, depicts colors by names such as red, blue, black, or light green.

    Images

    CSS Images Specification defines image-related data types, such as gradients. The following table lists all the images related data types:

    PropertyDescription
    <image>A URL pointing to an image or color gradient.

    2D Positioning

    The following table lists all the 2D Positioning related data types:

    PropertyDescription
    <position>Determines the position of an object region by providing a keyword value, such as top or left, or a <length-percentage>.

    Calculation Data Types

    CSS math functions use these data types in calculations. The following table lists all the calculation data types:

    PropertyDescription
    <calc-sum>A calculation is a series of calculated values separated by addition (+) and subtraction (-) operators. This data type requires that both values contain units.
    <calc-constant>Defines CSS keywords for numeric constants such as e and , which can be used in CSS math functions.

    Display

    The table given below lists all the display related data types:

    PropertyDescription
    <display-box>Determines if an element creates display boxes or not.
    <display-inside>Determines the inner display of an element, which specifies the formatting context type, for a non-replaced element.
    <display-internal>Determines the internal display values, which have relevance only to that particular layout model.
    <display-legacy>A single-keyword syntax has been used for display property in CSS 2, which required separate keywords for block-level and inline-level variants of the same layout model.
    <display-listitem>The keyword list-item makes the element to generate a ::marker pseudo-element with the content that is specified by the list-style properties, along with a main box of the specified type for its own contents.
    <display-outside>An element’s outer display type, which is essential in flow layout, is determined by the <display-outside> keywords.

    Other Data Types

    The table given below lists some more data types:

    PropertyDescription
    <absolute-size>Defines absolute font size in the font shorthand and font-size properties.
    <basic-shape>Defines different shapes used for properties such as clip-path, shape-outside, and offset-path.
    <blend-mode>Specifies the color scheme that should be used when elements overlap.
    <box-edge>Defines different box edges, such as content-box and border-box.
    <easing-function>Control the speed of a transition or animation between two states of an element.
    <filter-function>Signifies a graphical effect, which changes the appearance of an input image.
    <generic-family>Signifies the keyword values for generic font families.
    <gradient>Demonstrates a progressive transition between two or more colors.
    <ident>Signifies an arbitrary string that is used as an identifier.
    <line-style>Specifying how a line appears or doesn’t appear in a certain context are included in the <line-style> enumerated value type.
    <overflow>The keyword values used in relation to the shorthand overflow property and the longhand overflow-block, overflow-inline, overflow-x, and overflow-y properties are indicated by the enumerated value type <overflow>.
    <relative-size>Define a relative size to the calculated size of the parent element.
    <transform-function>The transformation functions are responsible for rotating, scaling (resizing), skewing (distorting), or moving an element in two-dimensional (2D) and three-dimensional (3D) space.
  • important Rule

    CSS !important rule is used to add more priority to a property than normal. In this tutorial we will learn !important rule and how to use it in CSS. Following is syntax of important rule.

    Syntax

    selector{property: value !important;}

    Table of Contents

    • What is CSS !important Rule?
    • Specificity in CSS
    • CSS !important Rule Example
    • CSS !important and Specificity
    • Override Inline Styles
    • Multiple Important Keyword
    • Custom Properties !important
    • Shorthand Properties !important

    What is CSS !important Rule?

    • An exclamation mark (!) followed by the word important (without space) tells the browser to prioritize that value for the property above all other declaration.
    • The !important rule will be applied regardless of specificity of property. We will discuss specificity later in this tutorial.
    • If multiple selectors use important keyword for a property, then the selector with high specificity will be considered to be applied.

    Specificity in CSS

    Specificity in CSS determines which styles are applied to an element when multiple rules could apply. For example, inline styles have highest priority, then id selector, then class selectors and then element selector.

    /* Element selector Styles */p{color: black;}/* Override the above style, Class have higher specificity */p.special{color: blue;}/* Using !important to force an override */p{color: red !important;}

    The above declaration make the text color of paragraph as red. The style of element selector is overridden by class selector, which then again overridden by important keyword.

    • Keep in mind that while ‘!important’ can be handy in specific cases, it’s best to use it only when truly needed.
    • Using ‘!important’ too frequently can make your code harder to manage and debug.
    • It’s a good practice to rely on proper CSS specificity and structure to prevent the excessive use of ‘!important’.

    CSS !important Rule Example

    The following example demonstrates the use of ‘!important’ which we saw above.

    Example

    <!DOCTYPE html><html><head><style>
    
        /* Element Selector Styles */
        p {
            color: black;
            font-weight: bold;
        }
        /* Using !important to force a color override */
        p {
            color: red <strong>!important</strong>;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt; 
        This paragraph will be red. Because the style of element 
        selector is overridden by important keyword.
    &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS !important and Specificity

    According to CSS specificity inline styles have highest priority, then id selector, then class selectors and then element selector. Which means the style written by element selectors can be override by class selectors, id selector and inline style respectively.

    Following example uses multiple selectors to apply color property to a paragraph but the element selector property having important keyword is applied to paragraph.

    Example

    <!DOCTYPE html><html><head><style>
    
        /*Multiple selectors for paragraph */
        p {
            color: black;
            font-weight: bold;
        }
        .special {
            color: blue;
        }
        #unique {
            color: darkgreen;
        }
        p {
            color: red <strong>!important</strong>;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;p id="unique" class="special"&gt;
        This paragraph will be red. Because element selector  
        will set color as black, class selector ".special" 
        will override this color to blue and id selector will 
        make it green. Finally important keyword is used at 
        last so this have more priority.
    &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Override Inline Styles

    Inline style have most priority over any selector in CSS. But important keyword can override inline CSS also. Lets see an example.

    Example

    <!DOCTYPE html><html><head><style>
    
            p {
                color: black <strong>!important</strong>; 
                font-weight: bold;
            }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;p style="color:red"&gt;
        Paragraph is black. Inline style is overridden by 
        important keyword
    &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Multiple Important Keyword

    When we apply multiple important keyword for a property in CSS using multiple selectors, the property which is inside the selector with high specificity is applied. Lets look at an example for this.

    Example

    <!DOCTYPE html><html><head><style>
    
        /*Multiple selectors for paragraph */
        p {
            color: black <strong>!important</strong>;
            font-weight: bold;
        }
        .special {
            color: blue <strong>!important</strong>;
        }
        #unique {
            color: darkgreen <strong>!important</strong>;
        }
        p {
            color: red <strong>!important</strong>;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;p id="unique" class="special"&gt;
        This paragraph will be darkgreen. Since important keyword 
        is present at every selectors, high priority selector 
        will be chosen. In this case it is id "#unique"
    &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS !important for Custom Properties

    When you add '!important' to a custom property, it means that this value is really important. The '!important' flag is not passed as part of the custom property value to the var() function.

    Example

    <!DOCTYPE html><html><head><style>
    
        :root {
            --primary-color: blue <strong>!important</strong>;
            --primary-color: red ;
        }
        .box {
            background-color: var(--primary-color) ;
            width: 200px;
            height: 200px;
        }
        p {
            color: var(--primary-color);
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div class="box"&gt;&lt;/div&gt;&lt;p&gt; Primary Color variable is Blue &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS !important on Shorthand Properties

    When you use '!important' with a shorthand property, it also applies importance to all its individual properties. The following examples are identical.This example:

    Example

    <!DOCTYPE html><html><head><style>
    
        p {
            /* Applies to all */
            font: 15px Arial, sans-serif <strong>!important</strong>;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;p style="font-size: 100px;"&gt;
        The font will set as per in CSS declaration. The font size of 
        100px will not be applied because important keyword is used 
        for shorthand property font. 
    &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

  • Image Sprites

    CSS Image Sprite combines multiple images into a single image file(the sprite image) and displays the images using coordinates inside the sprite image. It helps in reducing the number of server requests and improves the website performance.

    Image sprites are generally used for icons, buttons, and other smaller graphics on a website. CSS is then used to display specific parts of the sprite image as needed.

    How to Implement Image Sprite in CSS?

    We will follow the steps mentioned below to implement image sprites in CSS.

    • Create Sprite Image: First, we create an image containing all the individual images that you want to use as a sprite by using photo editing tools like Adobe Photoshop.
    • Determine Position of Images: Precisely note down the coordinates of the top-left corner of all the sub-images inside the main sprite image. This can later be used in CSS, to render that part of the image.
    • Display the Image: We have used CSS background-image property to display the sprite image on a webpage.
    • Adjust the position: We have used background-position to specify the top left corner of the inner image in the sprite image. Then we have used CSS height and width properties for specifying the dimensions from the top left corner that should be rendered.
    .sprite-icon{width: 75px;/* Set the width of the displayed image */height: 75px;/* Set the height of the displayed image */background-image:url('sprites.png');/* Path to sprite image */background-position: -40px -40px;/* Position of the individual image within the sprite */}

    In the above example, first we specified height and width sub image as 75px. Then we specified URL of sprite image, which contain all the inner images. Then we specified position of top-left corner of inner image using the background-position property as (-40px, -40px). Following diagram shows how inner image will be selected based on above values.

    img-sprite

    CSS Image Sprites Basic Example

    The following example demonstrates how to use CSS image sprites to display multiple images from a single image file.

    Example

    <!DOCTYPE html><html><head><style>
    
        img{
            height: 60px;
            width: auto;
            border: 3px solid;
        }
        .main{
            display: flex;
            justify-content: space-around;
        }
        .bootstrap, .html, .css {
            width: 150px;
            height: 150px;
            background-image: url('/css/images/devices.png');
            background-repeat: no-repeat;
            border: 5px solid;
        }
        .bootstrap {
            background-position: -5px -5px;
        }
        .html {
            background-position: -155px -5px;
        }
        .css {
            background-position: -277px -5px;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h3&gt;Original Image&lt;/h3&gt;&lt;img src="/css/images/devices.png"/&gt;&lt;h3&gt;Image sprites&lt;/h3&gt;&lt;div class="main"&gt;&lt;div class="bootstrap"&gt;&lt;/div&gt;&lt;div class="html"&gt;&lt;/div&gt;&lt;div class="css"&gt;&lt;/div&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Image Sprites Hover Effect

    The following example demonstrates the use of hover effects on image sprites where the images become slightly transparent when you hover over them.

    Example

    <!DOCTYPE html><html><head><style>
    
        img{
            height: 60px;
            width: auto;
            border: 3px solid;
        }
        .main{
            display: flex;
            justify-content: space-around;
        }
        .bootstrap, .html, .css {
            width: 150px;
            height: 150px;
            background-image: url('/css/images/devices.png');
            background-repeat: no-repeat;
            border: 5px solid;
        }
        .bootstrap {
            background-position: -5px -5px;
        }
        .html {
            background-position: -155px -5px;
        }
        .css {
            background-position: -277px -5px;
        }
        .bootstrap:hover, .html:hover, .css:hover {
            opacity: 0.7;
         }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h3&gt;Original Image&lt;/h3&gt;&lt;img src="/css/images/devices.png"/&gt;&lt;h3&gt;Image sprites&lt;/h3&gt;&lt;div class="main"&gt;&lt;div class="bootstrap"&gt;&lt;/div&gt;&lt;div class="html"&gt;&lt;/div&gt;&lt;div class="css"&gt;&lt;/div&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

  • Validations

    CSS Validation refer to process to checking correctness of CSS rules in a webpage. Validation is the process of checking something against a rule. When you are a beginner, it is very common that you will commit many mistakes in writing your CSS rules. How you will make sure whatever you have written is 100% accurate and up to the W3 quality standards?

    W3C CSS Validator is official CSS validator developed by World Wide Web Consortium. This validator checks your css by either file upload, direct input, or using URL.

    CSS Validation Example

    The image below shows css validation done by W3C:

    CSS Validation

    Validation Warnings

    When you validate your CSS, you may see warnings. These warnings do not stop your CSS from working, but they indicate that something is not perfect. Here are some common validation warnings:

    • Deprecated Properties: Some CSS properties are old and should not be used anymore. Its better to use newer alternatives.
    • Invalid Values: If you use a value that does not fit with the property, a warning will show up. Make sure to check the correct values for each property.
    • Redundant Code: Warnings may point out code that is not needed because it does not change anything. Cleaning this up can help your CSS be more efficient.
    • Selectors Too Specific: If your CSS selectors are too specific, they can make your code harder to read and maintain. Try to keep selectors simple.

    Why Validate Your CSS Code?

    Validating the stylesheet of a webpage is important for ensuring that website displays and functions correctly across different browsers and devices.

    • Improves Browser Compatibility: Validation makes sure your CSS follows the rules, so your webpage looks good on all browsers.
    • Enhances Performance: Clean and correct CSS helps your webpage load faster, while mistakes or extra code can slow it down.
    • Debugging Made Easier: Validating your CSS helps you find and fix mistakes, making it easier to manage your code.
    • SEO Benefits: Well-organized and correct CSS can improve the user experience and make your site faster. This way your site can get ranked easily in search engines.

  • Layouts

    CSS Layout is essential for defining the visual structure, organization, and responsiveness of a website. In this tutorial, we will explore various CSS techniques to create effective website layouts.

    Structure of Webpage Layout

    A webpage is made up of various sections like header, menus, content, and footer based on which there are many different layout designs available for developers.

    webpage-layout

    To know how to define a webpage structure, checkout our tutorial on HTML Layout. Here we explained each and every elements of a webpage layout. In this tutorial we will see how to style a webpage layout using CSS.

    Table of Contents

    • CSS Normal Layout Flow
    • CSS Float Layout
    • CSS Flex Layout
    • CSS Grid Layouts
    • CSS Positioning
    • CSS Responsive Layout

    CSS Normal Layout Flow

    Normal flow is the default layout mode where elements are positioned in the order they appear in the HTML document.

    • Block level elements like <div>, <p>, headings will stack vertically and takes up full width if not specified.
    • Inline elements like <span>, <strong> stack horizontally. You cannot alter height and width of these elements.
    • Inline block elements will behave like both inline and block. They will start from current line but you can alter it’s size.

    Let’s see an example for CSS normal layout flow

    Example

    <!DOCTYPE html><html><head><style>
    
        div, span{
            border: 2px solid;
            margin: 10px;
        }
        .inlineBlock{
            display: inline-block;
            height: 100px;
            width: 100px;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div&gt; Block Element &lt;/div&gt;&lt;div&gt; Block Element &lt;/div&gt;&lt;span&gt; Inline element &lt;/span&gt;&lt;span&gt; Inline element &lt;/span&gt;&lt;div&gt; Block Element &lt;/div&gt;&lt;span&gt; Inline element &lt;/span&gt;&lt;div class="inlineBlock"&gt;
        Inline Block Element
    &lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Float Layout

    Float Layout is used to position elements left or right in document flow. Main use of this layout system is to create two column layout and to wrap texts to either sides of image in webpage.

    .sidebar{float: left;width: 25%;}.main-content{float: right;width: 75%;}

    This layout create a sidebar at left side of the page occupying 25% of available width and main content at right with 75% width.

    In this example we will see how float is used with images to wrap text.

    Example

    <!DOCTYPE html><html><head><style>
    
        .float-left {
            float: left;
            margin-bottom: 20px;
            margin-right: 10px;
            border: 3px solid;
        }
        h3{
            clear: left;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;img src="/css/images/logo.png" class="float-left" &gt;&lt;p&gt;This text will wrap around the floated image.&lt;/p&gt;&lt;h3&gt;This text with float cleared&lt;/h3&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Flex Layout

    CSS Flex Layout organizes elements within a container along a single dimension, which can be either horizontally or vertically aligned.

    Following example uses flex-direction as row, means items will be arranged horizontally. For vertical arrangement you need to set flex direction as column.

    Example

    <!DOCTYPE html><html lang="en"><head><style>
    
        .container {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;
            height: 200px;
        }
        .item {
            background-color: lightcoral;
            padding: 20px;
            margin: 10px;
            border: 3px solid #ccc;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div class="container"&gt;&lt;div class="item"&gt;Item 1&lt;/div&gt;&lt;div class="item"&gt;Item 2&lt;/div&gt;&lt;div class="item"&gt;Item 3&lt;/div&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Grid Layouts

    CSS Grid Layout is a two-dimensional layout system used for organizing elements horizontally and vertical while developing responsive webpages.

    In the following example we define columns as '2fr 1fr 1fr', this means that first column should take 2 fraction of available space and rest two columns take 1 fraction of available space.

    Example

    <!DOCTYPE html><html lang="en"><head><style>
    
      .grid-container {
         display: grid;
         grid-template-columns: 2fr 1fr 1fr;
         grid-template-rows: 100px 100px 100px;
         gap: 20px; 
      }
      .grid-item {
         background-color: #4CAF50;
         border: 4px solid black;
         padding: 20px;
         text-align: center;
         color: white;
      }
    </style></head><body><div class="grid-container"><div class="grid-item"> Item 1 </div><div class="grid-item"> Item 2 </div><div class="grid-item"> Item 3 </div><div class="grid-item"> Item 4 </div><div class="grid-item"> Item 5 </div></div></body></html>

    CSS Positioning

    CSS Positioning helps to manipulate position of any element in a web page.

    Along with position property, other properties like top, bottom, left and right are used to control its exact position on the page. They specify the offsets of an element from its edges.

    Example

    <!DOCTYPE html><html lang="en"><head><style>
    
        *{
            padding: 15px;
        }
        .container {
            border: 1px solid #ccc;
        }
        .static-element {
            position: static;
            background-color: lightblue;
        }
        .relative-element {
            position: relative;
            top: 20px;  
            left: 30px; 
            background-color: lightgreen;
        }
        .normal-flow {
            background-color: lightcoral;
            margin: 10px 0;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div class="container"&gt;&lt;div class="static-element"&gt;
            This is a static element (default position).
        &lt;/div&gt;&lt;div class="relative-element"&gt;
            This element is relatively positioned 20px 
            down and 30px right.
        &lt;/div&gt;&lt;div class="normal-flow"&gt;
            This element is in the normal document 
            flow, after the relative element.
        &lt;/div&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Responsive Layout

    A Responsive webpage layout looks good in all the end user devices like phones, tablets and desktops. It will automatically adjust size and other features accordance with user device.

    In CSS the Media Queries are used to apply different CSS styles based on the screen size, resolution, and other characteristics of the user device.

    @media (width > 700px){/* Styles for screens that are at least 700px wide */}

    The following example demonstrates that when the screen width is between 600px and 800px, the background color changes to yellow and text color changes to red.

    Example

    <html><head><style>
    
    p {
        color: blue;
    }
    @media (600px &lt; width &lt; 800px) {
        p {
            background-color: yellow;
            color: red;
        }
    }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt; TutorialsPoint &lt;/h1&gt;&lt;p&gt; CSS Media Type - Screen &lt;/p&gt;&lt;p&gt; 
        Resize the browser size to see the effect. (Open HTML 
        compiler of TutorialsPoint and try there )
    &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>