Category: References

  • Units

    CSS Units define the measurement system used to specify the values. CSS offers a number of different units for expressing length and measurement. CSS unit is used to specify the property size for a page element or its content.

    There are a number of ways to specify and measure length in CSS. It is used to specify margins, padding, font size, width, height, border, etc.

    For example – font-size: 50px, here number 50 has a suffix px i.e., pixel, it is a CSS measurement unit.

    There should be no whitespace between the number and the unit. The unit can be left out when the value is 0.

    Length Units

    Length units can be categorized into two types:

    • Absolute units: Fixed unit lengths that does not depend on screen width.
    • Relative units: Responsive unit lengths that changes according to screen width.

    Absolute Length Units

    These units are categorized as fixed-length units, which means that lengths specified with absolute units maintain an exact, unchanged size on the screen.

    These units prove to be very effective when the browser has comprehensive information about the properties of the screen, the printer being used, or other appropriate user agents.Height: 2pxHeight: 2cmHeight: 2inHeight: 2pt

    The following table contains all the types of absolute units:

    UnitDescriptionEquivalent valueExample
    mmRefers to millimeter, it is used to specify the measurements in millimeters.1mm = 1/10th of 1cmfont-size: 10mm;
    cmRefers to centimeter, it is used to specify the measurements in centimeters.1cm = 37.8px = 25.2/64infont-size: 5cm;
    QRefers to Quarter-millimeters, it is used to specify the measurements in centimeters.1Q = 1/40th of 1cmfont-size: 5Q;
    inRefers to inches, it is used to specify the measurement in inches.1in = 2.54cm = 96pxfont-size: 1in;
    ptRefers to point, it is used to specify the measurements in points.1pt = 1/72 of 1infont-size: 20pt;
    pcRefers to picas, it is used to specify the measurement in picas.1pc = 1/6th of 1inwidth: 6pc;
    pxRefers to pixels, it is used to specify the measurement in pixels.1px = 1/96th of 1infont-size: 15px;

    Absolute units prove valuable for projects where responsiveness is not a priority. However, they are less beneficial for responsive websites because they do not adjust when screen dimensions change.

    Example

    Here is an example of absolute units (mm, cm, in, Q) used for font sizes:

    <html><head><style>
    
        .unit-mm {
            font-size: 5mm;
        }
        .unit-cm {
            font-size: 1cm;
        }
        .unit-inch {
            font-size: 0.5in;
        }
        .unit-quarter {
            font-size: 40Q;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h1 class="unit-mm"&gt; Font size 5mm &lt;/h1&gt;&lt;h1 class="unit-cm"&gt; Font size 1cm &lt;/h1&gt;&lt;h1 class="unit-inch"&gt; Font size 0.5inch &lt;/h1&gt;&lt;h1 class="unit-quarter"&gt; Font size 40Q &lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Relative Length Units

    Relative length units are measured in relation to other elements or viewport of the screen.

    Relative units are great for styling responsive websites because they can be adjusted proportionally based on window size or parent elements. These units define lengths relative to other length properties.Height: 3emHeight: 3exHeight: 3lhHeight: 3vh

    The following table contains all the types of relative units:

    UnitDescriptionExample
    emRelative to the font-size of the element.font-size: 4em;
    exRelative to the x-height of the current font.font-size: 4ex;
    chRelative to width of the "0".font-size: 4ch;
    remRelative to font-size of the root element.font-size: 2rem;
    lhIt is relative to the line height of the element.font-size: 4lh;
    rlhIt is relative to the line height of the root element.font-size: 4rlh;
    vhIt is relative to the height of the viewport. 1vh = 1% or 1/100 of the height of the viewport.font-size: 4vh;
    vwIt is relative to the width of the viewport. 1vw = 1% or 1/100 of the width of viewport.width: 4vw;
    vminIt is relative to the smaller dimension of the viewport. 1vmin = 1% or 1/100 of the viewport's smaller dimension.width: 4vmin;
    vmaxIt is relative to the larger dimension of the viewport. 1vmax = 1% or 1/100 of the viewport's larger dimension.width: 4vmax;
    vbIt is relative to the size of the initial containing block in the direction of the root element's block axis. 1vb = 1% of containing block's size (block axis).font-size: 4vb;
    viIt is relative to the size of the initial containing block in the direction of the root element's inline axis. 1vb = 1% of containing block's size (inline axis).font-size: 4vi;
    svw, svhIt is relative to the width and height of the smaller viewport. 1svw = 1% or 1/100 of the smaller viewport's width and 1svh = 1% or 1/100 of the smaller viewport's height.width: 40svw; height: 40svh;
    lvw, lvhIt is relative to the width and height of the larger viewport. 1lvw = 1% or 1/100 of the larger viewport's width and 1lvh = 1% or 1/100 of the larger viewport's height.width: 40lvw; height: 40lvh;
    dvw, dvhIt is relative to the width and height of the dynamic viewport. 1dvw = 1% or 1/100 of the dynamic viewport's width and 1dvh = 1% or 1/100 of the dynamic viewport's height.width: 40dvw; height: 40dvh;

    Example

    Here is an example of relative units (em, rem, vw, vh, %) used for font sizes:

    <html><head><style>
    
        .unit-em {
            font-size: 2em;
        }
        .unit-rem {
            font-size: 1.5rem;
        }
        .unit-vw {
            font-size: 5vw;
        }
        .unit-vh {
            font-size: 5vh;
        }
        .unit-percent {
            font-size: 150%;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h1 class="unit-em"&gt;Font size 2em &lt;/h1&gt;&lt;h1 class="unit-rem"&gt;Font size 1.5rem &lt;/h1&gt;&lt;h1 class="unit-vw"&gt;Font size 5vw &lt;/h1&gt;&lt;h1 class="unit-vh"&gt;Font size 5vh &lt;/h1&gt;&lt;h1 class="unit-percent"&gt;Font size 150% &lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Units px (Pixel) and em (indicates size relative to the size of the font) are two of the measurement units of length. In order to convert px to em, try our free CSS - PX to EM Converter.

  • Color References

    The following table shows the 16 color names that were introduced in HTML 3.2, to support the 16 colors that 8-bit graphics cards offered. Same set of color can be used in CSS −

    Color NameHex ValueColorShow
    aqua#00ffffDemo
    black#000000Demo
    blue#0000ffDemo
    fuchsia#ff00ffDemo
    green#008000Demo
    gray#808080Demo
    lime#00ff00Demo
    maroon#800000Demo
    navy#000080Demo
    olive#808000Demo
    purple#800080Demo
    red#ff0000Demo
    silver#c0c0c0Demo
    teal#008080Demo
    white#ffffffDemo
    yellow#ffff00Demo

    There are other colors, which are not part of HTML or XHTML but they are supported by most of the versions of IE or Netscape. These color names can be used in CSS as well.

    Color NameHex ValueColorShow
    aliceblue#f0f8ffDemo
    antiquewhite#faebd7Demo
    aquamarine#7fffd4Demo
    azure#f0ffffDemo
    beige#f5f5dcDemo
    bisque#ffe4c4Demo
    blanchedalmond#ffebcdDemo
    blueviolet#8a2be2Demo
    brown#a52a2aDemo
    burlywood#deb887Demo
    cadetblue#5f9ea0Demo
    chartreuse#7fff00Demo
    chocolate#d2691eDemo
    coral#ff7f50Demo
    cornflowerblue#6495edDemo
    cornsilk#fff8dcDemo
    crimson#dc143cDemo
    cyan#00ffffDemo
    darkblue#00008bDemo
    darkcyan#008b8bDemo
    darkgoldenrod#b8860bDemo
    darkgray#a9a9a9Demo
    darkgreen#006400Demo
    darkkhaki#bdb76bDemo
    darkmagenta#8b008bDemo
    darkolivegreen#556b2fDemo
    darkorange#ff8c00Demo
    darkorchid#9932ccDemo
    darkred#8b0000Demo
    darksalmon#e9967aDemo
    darkseagreen#8fbc8fDemo
    darkslateblue#483d8bDemo
    darkslategray#2f4f4fDemo
    darkturquoise#00ced1Demo
    darkviolet#9400d3Demo
    deeppink#ff1493Demo
    deepskyblue#00bfffDemo
    dimgray#696969Demo
    dodgerblue#1e90ffDemo
    firebrick#b22222Demo
    floralwhite#fffaf0Demo
    forestgreen#228b22Demo
    gainsboro#dcdcdcDemo
    ghostwhite#f8f8ffDemo
    gold#ffd700Demo
    goldenrod#daa520Demo
    gray#808080Demo
    greenyellow#adff2fDemo
    honeydew#f0fff0Demo
    hotpink#ff69b4Demo
    indianred#cd5c5cDemo
    indigo#4b0082Demo
    ivory#fffff0Demo
    khaki#f0e68cDemo
    lavender#e6e6faDemo
    lavenderblush#fff0f5Demo
    lawngreen#7cfc00Demo
    lemonchiffon#fffacdDemo
    lightblue#add8e6Demo
    lightcoral#f08080Demo
    lightcyan#e0ffffDemo
    lightgoldenrodyellow#fafad2Demo
    lightgreen#90ee90Demo
    lightgrey#d3d3d3Demo
    lightpink#ffb6c1Demo
    lightsalmon#ffa07aDemo
    lightseagreen#20b2aaDemo
    lightskyblue#87cefaDemo
    lightslategray#778899Demo
    lightsteelblue#b0c4deDemo
    lightyellow#ffffe0Demo
    limegreen#32cd32Demo
    linen#faf0e6Demo
    magenta#ff00ffDemo
    mediumblue#0000cdDemo
    mediumorchid#ba55d3Demo
    mediumpurple#9370dbDemo
    midnightblue#191970Demo
    mistyrose#ffe4e1Demo
    moccasin#ffe4b5Demo
    oldlace#fdf5e6Demo
    orange#ffa500Demo
    orchid#da70d6Demo
    peachpuff#ffdab9Demo
    peru#cd853fDemo
    pink#ffc0cbDemo
    plum#dda0ddDemo
    purple#800080Demo
    rosybrown#bc8f8fDemo
    royalblue#4169e1Demo
    salmon#fa8072Demo
    sandybrown#f4a460Demo
    seagreen#2e8b57Demo
    sienna#a0522dDemo
    skyblue#87ceebDemo
    slateblue#6a5acdDemo
    steelblue#4682b4Demo
    tan#d2b48cDemo
    thistle#d8bfd8Demo
    tomato#ff6347Demo
    violet#ee82eeDemo
    wheat#f5deb3Demo
    whitesmoke#f5f5f5Demo
    yellow#ffff00Demo
    yellowgreen#9acd32Demo

  • Functions Reference

    This chapter is a CSS functions reference page and lists down each functions used in CSS. For detailed information about any function, visit respective function pages.

    FunctionDescription
    acos()CSS acos() function returns the inverse cosine of a value in the range -1 and 1.
    asin()CSS asin() function returns the inverse sine of a number between -1 and 1.
    atan()CSS atan() function returns the inverse tangent of a number between -infinity and infinity.
    atan2()CSS atan2() function returns the inverse tangent of two values between -infinity and infinity.
    attr()CSS attr() function returns the value of an attribute of the selected element.
    blur()CSS blur() function applies a Gaussian blur to the elements on which it is applied.
    brightness()CSS brightness() function sets the brightness of an element.
    calc()CSS calc() function performs calculations to determine CSS property values.
    circle()CSS circle() function defines a circle.
    clamp()CSS clamp() function sets a value for adjusting responsively between a minimum and maximum
    color()CSS color() function allows a color to be specified in a particular, specified color space.
    color-mix()CSS color-mix() function is used to mix two color values by a given amount.
    conic-gradient()CSS conic-gradient() is used to creates a conic gradient.
    contrast()CSS contrast() function sets the contrast of an element.
    cos()CSS cos() function returns the cosine of an angle.
    counter()CSS counter() function returns the current value of the counter.
    counters()CSS counters() function returns the current values of the nested and named counters.
    cubic-bezier()CSS cubic-bezier() function defines a custom cubic bezier curve for animations.
    drop-shadow()CSS drop-shadow() function applies a drop shadow effect to an image.
    ellipse()CSS ellipse() function is used to define an ellipse.
    env()CSS env() function adds a value to a user-defined environment variable in your CSS.
    exp()CSS exp() function returns the value of e raised to the power of a given number.
    fit-content()CSS fit-content() function resizes an element based on its content.
    grayscale()CSS grayscale() function sets the grayscale of an image.
    hsl() / hsla()CSS hsl() function defines a color using the Hue-Saturation-Lightness model, with an optional alpha that represents the opacity.
    hue-rotate()CSS hue-rotate() function rotates the hue of an element’s colors.
    hwb()CSS hwb() function defines a color using the Hue-Whiteness-Blackness model, with an optional alpha that represents the opacity.
    hypot()CSS hypot() function returns the square root of the sum of the squares of the numbers.
    inset()CSS inset() function defines a rectangle at the specified inset distances from each side of the reference box.
    invert()CSS invert() function inverts the colors of an element.
    lab()CSS lab() function expresses a color in CIE L*a*b color space.
    lch()CSS lch() function expresses a color in LCH(Lightness Chroma Hue) color space.
    linear-gradient()CSS linear-gradient() function is used to create a linear gradient.
    log()CSS log() function returns the natural logarithm (e) of a given number.
    matrix()CSS matrix() function defines a 2D transformation with homogeneous coordinates.
    matrix3d()CSS matrix3d() function defines a 3D transformation using a 4×4 matrix of 16 values.
    max()CSS max() function specify the largest (most positive) value from a list of comma-separated expressions.
    min()CSS min() function specify the lowest value from a list of comma-separated expressions.
    minmax()CSS minmax() function defines a size range for CSS grid columns or rows.
    mod()CSS mod() function calculates the modulus of two numbers when divided.
    opacity()CSS opacity() function function sets the transparency level of an element.
    oklab()CSS oklab() function expresses a color in the oklab color space.
    oklch()CSS oklch() function expresses a color in oklch color space.
    perspective()CSS perspective() function defines a perspective view for a 3D transformed element.
    polygon()CSS polygon() function is used to define a polygon.
    pow()CSS pow() function returns the value of a base raised to the power of a number.
    radial-gradient()CSS radial-gradient() function is used to create a radial gradient.
    repeat()CSS repeat() function is used for repeating columns or rows in a CSS grid.
    repeating-conic-gradient()CSS repeating-conic-gradient() repeats a conic gradient.
    repeating-linear-gradient()CSS repeating-linear-gradient() repeats a linear gradient.
    repeating-radial-gradient()CSS repeating-radial-gradient() repeats a radial gradient.
    rgb()CSS rgb() function sets the colors using the Red-Green-Blue model (RGB) value.
    rotate()CSS rotate() function defines a 2D rotation of an element.
    rotate3d()CSS rotate3d() function rotates an element around a fixed axis on the three-dimensional surface.
    rotateX()CSS rotateX() function rotates an element around the x-axis.
    rotateY()CSS rotateY() function rotates an element around the y-axis.
    rotateZ()CSS rotateZ() function rotates an element around the z-axis.
    round()CSS round() function returns a rounded number.
    saturate()CSS saturate() function sets the saturation level of an element.
    scale()CSS scale() function applies a scaling transformation to an element on the two-dimensional plane.
    scale3d()CSS scale3d() function applies a scaling transformation to an element on the three-dimensional plane.
    scaleX()CSS scaleX() function applies a scaling transformation to an element along the x-axis.
    scaleY()CSS scaleY() function applies a scaling transformation to an element along the y-axis.
    scaleZ()CSS scaleZ() function applies a scaling transformation to an element along the z-axis.
    sepia()CSS sepia() function applies and sets a sepia (warm, yellowish/brownish) effect to an element.
    sin()CSS sin() function calculates the sine of a given number and returns a result in the range -1 to 1.
    skew()CSS skew() function specifies a transformation that slants an element on the 2D plane.
    skewX()CSS skewX() function specifies a transformation that slants an element horizontally on the 2D plane.
    skewY()CSS skewY() function specifies a transformation that slants an element vertically on the 2D plane.
    sqrt()CSS sqrt() function returns the square root of a given number.
    tan()CSS tan() function returns the tangent of a number.
    translate()Re-positions an element along the x- and y-axis
    translateX()CSS translateX() function translates, or moves, an element horizontally along the X-axis.
    translateY()CSS translateY() function translates, or moves, an element vertically along the Y-axis.
    url()CSS url() function is used to include a file in the HTML document.
    var()CSS var() function is used to insert the value of a custom property.
  • Cheat Sheet

    CSS stands for Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended to simplify the process of making web pages presentable.

    What is CSS Cheat Sheet?

    CSS cheat sheet is a collection of all the CSS properties and selectors that can be used to design any website. In this sheet we will provide mostly used CSS properties and related code snippets of below listed topics.

    Table of Content

    • CSS Selectors
    • Font Properties
    • Text Properties
    • Padding Properties
    • Margin Properties
    • Background Properties
    • Shadow Properties
    • Border Properties
    • CSS Flexbox
    • CSS Grid
    • Gradient
    • Classification Properties
    • CSS Functions
    • Media Queries

    Basics of CSS

    CSS specify how an HTML element should be displayed on the web page. If you think of the human body as a web page then CSS is styling part of the body. Like color of the eyes, size of the nose, skin tone, etc.

    Syntax

    selector{property: value;}

    Ways to use CSS

    There are three ways to use CSS into your HTML document.

    • Inline CSS: Inline CSS are directly applied on the HTML elements using style attribute.
    • Internal CSS: Internal CSS are defined in the HTML head section inside of <style> tag to let the browser know where to look for the CSS.
    • External CSS: External CSS are defined in a separate file that contains only CSS properties, this is the recommended way to use CSS when you are working on projects.

    CSS Selectors

    CSS Selectors are used to select the HTML elements you want to style on a web page. They allow you to target specific elements or groups of elements to apply styles like colors, fonts, margins, and more.

    Universal Selectors

    It is used to select all elements of the HTML.

    *{color: blue;}

    Element Selectors

    This is used to select particular HTML elements like p, span, header, etc.

    div{border: 5px inset gold;}

    Class Selectors

    This is used to select class defined by your own.

    .myClass{background-color: #04af2f;}

    Id Selectors

    This is used to select id defined by your own.

    .myId{background-color: #04af2f;}

    Attribute Selectors

    This is used to select particular HTML attributes.

    a[href]{font-size: 2em;}

    Group Selectors

    This is used to select multiple elements and style them together.

    h3,h4{text-align: center;}

    Pseudo-element Selectors

    This is used to select Pseudo-element.

    p::before{content:"Note: ";font-weight: bold;}

    Pseudo-class Selectors

    This is used to select Pseudo-class.

    a:hover{background-color: peachpuff;}

    Descendant Selectors

    This is used in css to style all the tags which are child of a particular specified tag.

    div p{color: blue;}

    Child Selectors

    This is used to select all the direct child of a particular element.

    div>p{color: blue;}

    Adjacent Sibling Selectors

    This is used to select an element that is immediately preceded by a specified element.

    div + p{color: blue;}

    General Sibling Selectors

    This is used to select all the element that is preceded by a specified element.

    div~p{color: blue;}

    Font Properties

    CSS Font is a set of text characters with a consistent design and style. It includes the shape, size, weight, and other attributes of the characters in a typeface.

    font

    Shorthand font property.

    p{font: oblique small-caps
    
          bold 20px Arial, sans-serif;}</pre>

    font-family

    CSS font-family specifies the font family or list of font families to be used for text.

    #para1{font-family: verdana, georgia;}

    font-feature-settings

    CSS font-feature-settings controls advanced typographic features in OpenType fonts.

    p{font-feature-settings:'smcp', off;}

    font-kerning

    CSS font-kerning determines the way specific pairs of letters are spaced.

    #nokern{font-kerning: none;}

    font-language-override

    CSS font-language-override Overrides the typeface behavior for a particular language.

    .text{font-language-override:"DAN";}

    font-optical-sizing

    CSS font-optical-sizing sets whether rendering of text should be optimized to view at different sizes.

    .myDiv{font-optical-sizing: auto;}

    font-palette

    CSS font-palette allows the usage of one of the various palettes that are contained in a font.

    font-palette: normal | light | dark | <palette-name> | <integer>;

    font-size

    CSS font-size sets the size of the text.

    font-size: medium | xx-small | x-small | small | large | x-large | xx-large | smaller | larger | length | percentage | initial | inherit;

    font-size-adjust

    CSS font-size-adjust specifies a font's aspect value (numeric ratio) that controls its x-height.

    font-size-adjust: number|none|initial|inherit;

    font-stretch

    CSS font-stretch adjusts the width of the text (condensed or expanded).

    font-stretch: ultra-condensed | extra-condensed | condensed | semi-condensed | normal | semi-expanded | expanded | extra-expanded | ultra-expanded | percentage | initial | inherit;

    font-style

    CSS font-style specifies the style of the text, such as "italic", "oblique", or "normal".

    font-style: normal | italic | oblique | initial | inherit;

    font-weight

    CSS font-weight sets the thickness or boldness of the text.

    font-weight: normal | bold | bolder | lighter | number | initial | inherit;

    font-synthesis

    CSS font-synthesis is a shorthand font-synthesis property.

    font-synthesis: none | weight | style | small-caps | position | initial | inherit;

    font-synthesis-small-caps

    CSS font-synthesis-small-caps determines whether or not the browser should synthesize the small-caps typeface, that is missing in a font-family.

    font-synthesis-small-caps: auto | none | initial | inherit;

    font-synthesis-style

    CSS font-synthesis-style determines whether or not the browser should synthesize the oblique typeface, that is missing in a font-family.

    font-synthesis-style: auto | none | initial | inherit;

    font-synthesis-weight

    CSS font-synthesis-weight determines whether or not the browser should synthesize the bold typeface, that is missing in a font-family.

    font-synthesis-weight: auto | none | initial | inherit;

    font-variant

    CSS font-variant controls the use of small caps for lowercase letters in the text.

    font-variant: normal|small-caps|initial;

    font-variant-alternates

    CSS font-variant-alternates controls the usage of alternate glyphs.

    font-variant-alternates: normal | historical-forms | stylistic() | styleset() | character-variant() | swash() | ornaments() | annotation();

    font-variant-caps

    CSS font-variant-caps controls the usage of alternate glyphs for capital letters.

    font-variant-caps: normal|small-caps|all-small-caps|petite-caps|all-petite-caps|unicase|titling-caps|initial|inherit|unset;

    font-variant-east-asian

    CSS font-variant-east-asian controls the usage of alternate glyphs for East-Asian scripts like Chinese and Japanese.

    font-variant-east-asian: normal | ruby;

    font-variant-ligatures

    CSS font-variant-ligatures controls the textual content of element as to which ligature or contextual form should be used.

    font-variant-ligatures: normal | none | <common-lig-values>" | <discretionary-lig-values> | <historical-lig-values> | <contextual-alt-values>;

    font-variant-numeric

    CSS font-variant-numeric controls the usage of alternate glyphs for numbers, fractions and ordinal markers.

    font-variant-numeric: normal | ordinal | slashed-zero | lining-nums | oldstyle-nums | proportional-nums | tabular-nums | diagonal-fractions | stacked-fractions;

    font-variant-position

    CSS font-variant-position controls the usage of alternate, smaller glyphs, positioned as superscript or subscript.

    font-variant-position: normal | sub | super;

    font-variation-settings

    CSS font-variation-settings specifies the four-letter axis names of variable font characteristics.

    font-variation-settings: normal | <string><integer>;

    Text Properties

    text refers to a piece of written or printed information in the form of words or characters that can be read and understood. Texts can include content such as books, articles, emails, messages, web pages, etc.

    Styling a text involves modifying its appearance to make it more visually appealing or to convey a particular message. This chapter demonstrates how to manipulate text using CSS properties.

    color

    CSS color sets the color of an element.

    color: color | initial | inherit;

    direction

    CSS direction defines direction of the flow of an element's content.

    direction: ltr | rtl | initial | inherit;

    line-height

    CSS line-height sets the distance between adjacent text baselines.

    line-height: normal | length | number | percentage | initial | inherit;

    text-align

    CSS text-align sets the text alignment style for an element.

    text-align: left | right | center | justify | initial | inherit;

    text-decoration

    CSS text-decoration defines any decoration for the text; values may be combined.

    text-decoration: none | underline | overline | line-through | blink | initial | inherit;

    text-indent

    CSS text-indent defines the indentation of the first line of text in an element; default is 0.

    text-indent: length | percentage | initial | inherit;

    text-shadow

    CSS text-shadow creates text drop shadows of varying colors and offsets.

    text-shadow: <h-shadow><v-shadow> blur-radius color | none | initial | inherit;

    text-transform

    CSS text-transform transforms the text in the element accordingly.

    text-transform: none | capitalize | uppercase | lowercase | full-width | full-width-kana | unset | initial | inherit;

    vertical-align

    CSS vertical-align sets the vertical positioning of an element.

    vertical-align: baseline | sub | super | top | text-top | middle | bottom | text-bottom | length | percentage | initial | inherit;

    white-space

    CSS white-space defines how whitespace within an element is handled.

    white-space: normal | nowrap | pre | pre-wrap | pre-line | break-spaces | initial | inherit;

    word-spacing

    CSS word-spacing inserts additional space between words.

    word-spacing: length | normal | initial | inherit;

    Padding Properties

    CSS padding defines the space between an element's content and its border.

    padding

    CSS padding is a shorthand for all padding properties. We can set padding for all four sides using padding shorthand property.

    padding: padding-top padding-right padding-bottom padding-left | auto | initial | inherit;

    padding-top

    CSS Padding-Top sets the width of the padding on the top of an element.

    padding-top: length | percentage | auto;

    padding-right

    CSS Padding-Right sets the width of the padding on the right of an element.

    padding-right: length | percentage | auto;

    padding-bottom

    CSS Padding-Bottom sets the width of the padding on the bottom of an element.

    padding-bottom: length | percentage | auto;

    padding-left

    CSS Padding-Left sets the width of the padding on the left of an element.

    padding-left: length | percentage | auto;

    Margin Properties

    CSS margin property is used to create space around an element, outside of its border.

    margin

    CSS Margin property is a shorthand property for defining values of properties: margin-top, margin-right, margin-bottom and margin-left in one single statement

    margin: margin-top margin-right margin-bottom margin-left | auto | initial | inherit;

    Margin-Top

    CSS margin-top sets the space outside the element's top border.

    margin-top: length | percentage | auto;

    Margin-Right

    CSS margin-right sets the space outside the element's right border.

    margin-right: length | percentage | auto;

    Margin-Bottom

    CSS margin-bottom sets the space outside the element's bottom border.

    margin-bottom: length | percentage | auto;

    Margin-Left

    CSS margin-left sets the space outside the element's left border.

    margin-left: length | percentage | auto;

    Background Properties

    CSS background properties are used to manipulate the background of elements. It can be used to apply a single background image or multiple background images, as well as defining the background color, size, position, repeat behavior, and other related properties.

    background

    CSS background is shorthand for background-related properties.

    background: color | image | position | size | repeat | attachment | origin | clip | initial | inherit;

    background-attachment

    CSS background-attachment specifies the position of the background relative to the viewport, either fixed or scrollable.

    background-attachment: scroll | fixed | local | initial | inherit;

    background-clip

    CSS background-clip controls how far a background image extends beyond the element's padding or content box.

    background-clip: border-box | padding-box | content-box | initial | inherit;

    background-color

    CSS background-color sets the background color of an element.

    background-color: color | transparent | initial | inherit;

    background-image

    CSS background-image sets one or more background image(s) on an element.

    background-image:url(imageURL) | none | initial | inherit;

    background-origin

    CSS background-origin sets the origin of the background.

    background-origin: border-box | padding-box | content-box | initial | inherit;

    background-position

    CSS background-position sets the initial position of each image in a background.

    background-position: value | initial | inherit;

    Note: The values are: <left top, left center, left bottom, right top, right center, right bottom, center top, center center, and center bottom>, <x% y%>, and <xpos ypos>.

    background-position-x

    CSS background-position-x sets the initial horizontal position of each image in a background.

    background-position-x: left | center | right | length | percentage | initial | inherit;

    background-position-y

    CSS background-position-y sets the initial vertical position of each image in a background.

    background-position-y: top | center | bottom | length | percentage | initial | inherit;

    background-repeat

    CSS background-repeat controls the repetition of an image in the background.

    background-repeat: repeat | repeat-x | repeat-y | no-repeat | space | round | initial | inherit;

    background-size

    CSS background-size controls the size of the background image.

    background-size: auto | length | percentage | cover | contain | initial | inherit;

    background-blend-mode

    CSS background-blend-mode determines how an element's background images blend with each other.

    background-blend-mode: normal | multiply | screen | overlay | darken | lighten | color-dodge | color-burn | hard-light | soft-light | difference | exclusion | hue | saturation | luminosity | color | initial | inherit;

    Shadow Properties

    There are two types of shadow properties existed in CSS as mentioned and described below.

    • Text Shadow: This is used to add a shadow effect to text. It allows you to specify the color, offset, blur-radius, and spread-radius of the shadow.
    • Box Shadow: This is used to add shadow effect around an element. One or more shadow effects can be added, separated by commas.

    text-shadow

    CSS text-shadow is used to add a shadow effect to text.

    text-shadow: <h-shadow><v-shadow> blur-radius color | none | initial | inherit;

    box-shadow

    CSS box-shadow is used to add a shadow effect around an element.

    box-shadow: none | h-offset v-offset blur spread color | inset | initial | inherit;

    Border Properties

    Border properties are used to create a border around an element, such as a div, image, or text. It allows you to customize the appearance of the border, including its color, width, and style.

    border

    CSS border sets all the border properties in one declaration.

    border: border-width border-style border-color | initial | inherit;

    border-bottom

    CSS border-bottom sets the bottom border of an element.

    border-bottom: border-width border-style border-color | initial | inherit;

    border-bottom-color

    CSS border-bottom-color sets the color of the bottom border of an element.

    border-bottom-color: color | transparent | initial | inherit;

    border-bottom-width

    CSS border-bottom-width sets the width of the bottom border of an element.

    border-bottom-width: length | thin | medium | thick | initial | inherit;

    border-bottom-style

    CSS border-bottom-style sets the style of the bottom border of an element.

    border-bottom-style: none | solid | dotted | dashed | double | groove | ridge | inset | outset | initial | inherit;

    border-color

    CSS border-color sets the color of the border of an element.

    border-color: color | transparent | initial | inherit;

    border-left

    CSS border-left sets the left border of an element.

    border-left: border-width border-style border-color | initial | inherit;

    border-left-color

    CSS border-left-color sets the color of the left border of an element.

    border-left-color: color | transparent | initial | inherit;

    border-left-width

    CSS border-left-width sets the width of the left border of an element.

    border-left-width: length | thin | medium | thick | initial | inherit;

    border-left-style

    CSS border-left-style sets the style of the left border of an element.

    border-left-style: none | solid | dotted | dashed | double | groove | ridge | inset | outset | initial | inherit;

    border-right

    CSS border-right sets the right border of an element.

    border-right: border-width border-style border-color | initial | inherit;

    border-right-color

    CSS border-right-color sets the color of the right border of an element.

    border-right-color: color | initial | inherit;

    border-right-width

    CSS border-right-width sets the width of the right border of an element.

    border-right-width: length | thin | medium | thick | initial | inherit;

    border-right-style

    CSS border-right-style sets the style of the right border of an element.

    border-right-style: none | solid | dotted | dashed | double | groove | ridge | inset | outset | initial | inherit;

    border-style

    CSS border-style sets the style of the border of an element.

    border-style: none | solid | dotted | dashed | double | groove | ridge | inset | outset | initial | inherit;

    border-top

    CSS border-top sets the top border of an element.

    border-top: border-width border-style border-color | initial | inherit;

    border-top-color

    CSS border-top-color sets the color of the top border of an element.

    border-top-color: color | initial | inherit;

    border-top-width

    CSS border-top-width sets the width of the top border of an element.

    border-top-width: length | thin | medium | thick | initial | inherit;

    border-top-style

    CSS border-top-style sets the style of the top border of an element.

    border-top-style: none | solid | dotted | dashed | double | groove | ridge | inset | outset | initial | inherit;

    border-width

    CSS border-width sets the width of the border of an element.

    border-width: length | thin | medium | thick | initial | inherit;

    border-image

    CSS border-image sets the border image for an element.

    border-image: source slice width outset repeat | initial | inherit;

    border-image-outset

    CSS border-image-outset sets the image outset (how far the border image area extends beyond the border box).

    border-image-outset: length | initial | inherit;

    border-image-repeat

    CSS border-image-repeat defines whether the border image should be repeated, rounded, spaced, or stretched.

    border-image-repeat: stretch | repeat | round | space | initial | inherit;

    border-image-source

    CSS border-image-source sets the source/path of an image to be used as a border for an element.

    border-image-source: image | none | initial | inherit;

    border-image-slice

    CSS border-image-slice defines how to slice an image for use in a border.

    border-image-slice: number | percentage | fill | initial | inherit;

    border-image-width

    CSS border-image-width sets the width of the image to be used as a border.

    border-image-width: length |number | percentage | auto | initial | inherit;

    CSS Flexbox

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

    flex-direction

    CSS flex-direction sets the flex direction of the flex items.

    flex-direction: row | row-reverse | column | column-reverse | initial | inherit;

    flex-wrap

    CSS flex-wrap sets whether flex items should wrap onto the next line.

    flex-wrap: nowrap | wrap | wrap-reverse | initial | inherit;

    justify-content

    CSS justify-content sets the alignment of flex items along the main axis.

    justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly | initial | inherit;

    align-items

    CSS align-items sets the alignment of flex items along the cross axis.

    align-items: normal | stretch | flex-start | flex-end | center | baseline | initial | inherit;

    align-content

    CSS align-content sets the alignment and spacing of flex lines within the flex container.

    align-content: stretch | flex-start | flex-end | center | space-between | space-around | space-evenly | initial | inherit;

    flex-flow

    CSS flex-flow sets both the flex-direction and flex-wrap properties.

    flex-flow: flex-direction flex-wrap | initial | inherit;

    flex-grow

    CSS flex-grow sets a flex item to grow within a flex container.

    flex-grow: number | initial | inherit;

    flex-shrink

    CSS flex-shrink sets a flex item to shrink in size to fit the available space.

    flex-shrink: number | initial | inherit;

    flex-basis

    CSS flex-basis sets the initial size of a flex item.

    flex-basis: number auto | initial | inherit;

    flex

    CSS flex is a shorthand property that combines flex-grow, flex-shrink, and flex-basis.

    flex: flex-grow flex-shrink flex-basis | auto | initial | inherit;

    align-self

    CSS align-self sets the alignment of a specific flex item along the cross-axis.

    align-self: auto | flex-start | flex-end | center | baseline | stretch | initial | inherit;

    order

    CSS order is used to specify the order in which flex items appear inside their flex container.

    order: number | initial | inherit;

    CSS Grid

    CSS Grid is a convenient and concise way to define the grid layout of an element.

    display

    CSS display defines whether an element is a grid container or an inline grid container.

    display: grid | inline-grid | initial | inherit;

    gap

    CSS gap defines the gap between rows and columns.

    gap: row-gap column-gap | initial | inherit;

    grid-area

    CSS grid-area defines the location and size of the grid item within a grid layout.

    grid-area: grid-row-start / grid-column-start / grid-row-end / grid-column-end | item name | initial | inherit;

    grid-column

    CSS grid-column controls the placement of a grid item within the grid container in the column direction.

    grid-column: auto | grid-column-start | grid-column-end | initial | inherit;

    grid-row

    CSS grid-row controls the placement of a grid item within the grid container in the row direction.

    grid-row: auto | grid-row-start / grid-row-end | initial | inherit;

    grid-template

    CSS grid-template specifies the grid columns, grid rows, and grid areas.

    grid-template: none | grid-template-rows / grid-template-columns | grid-template-areas | initial | inherit;

    grid-auto-columns

    CSS grid-auto-columns determines the size of automatically generated grid column tracks or a pattern of such tracks.

    grid-auto-columns: auto | length | percentage | max-content | min-content | minmax(min,max) | fit-content() | initial | inherit;

    grid-auto-rows

    CSS grid-auto-rows determines the size of automatically generated grid row tracks or a pattern of such tracks.

    grid-auto-rows: auto | length | percentage | max-content | min-content | minmax(min, max)| fit-content() | initial | inherit;

    grid-auto-flow

    CSS grid-auto-flow specifies the arrangement of the grid items within the grid.

    grid-auto-flow: row | column | dense | row dense | column dense | initial | inherit;

    Gradient

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

    CSS defines three types of gradients.

    Linear Gradient

    Goes from left to right, up to down or diagonally.

    linear-gradient()/* to right, black, yellow, green */

    Radial Gradient

    Start from center to edges.

    radial-gradient()/* circle, black, yellow, green */

    Conic Gradient

    Revolve around a center point.

    conic-gradient()/* black, yellow, green */

    Classification Properties

    CSS classification properties allow you to control how to display an element, set where an image will appear in another element, position an element relative to its normal position, position an element using an absolute value, and how to control the visibility of an element.

    clear

    CSS clear sets which margins of an element must not be adjacent to a floating element; the element is moved down until that margin is clear.

    clear: none | left | right | both | inline-start | inline-end | initial | inherit;

    cursor

    CSS cursor defines the shape of the cursor.

    cursor: auto | default | pointer | text | wait | crosshair | move | not-allowed | grab;

    Code Example:

    <html>
    <head>
    
    &lt;title&gt;CSS Cursor Property&lt;/title&gt;
    &lt;style&gt;
        h2{padding: 5px;background-color: #04af2f;color: white;text-align: center;}.demo-cursor{display: inline-block;background-color: LightYellow;width: 100px;height: 100px;margin: 10px;border: 3px solid #ccc;cursor: pointer;}h3{text-align: center;}.default{cursor: default;}.auto{cursor: auto;}.crosshair{cursor: crosshair;}.pointer{cursor: pointer;}.move{cursor: move;}.text{cursor: text;}.wait{cursor: wait;}.help{cursor: help;}.not-allowed{cursor: not-allowed;}.progress{cursor: progress;}.alias{cursor: alias;}.copy{cursor: copy;}.no-drop{cursor: no-drop;}.e-resize{cursor: e-resize;}.n-resize{cursor: n-resize;}.ne-resize{cursor: ne-resize;}.nw-resize{cursor: nw-resize;}.s-resize{cursor: s-resize;}.se-resize{cursor: se-resize;}.sw-resize{cursor: sw-resize;}.w-resize{cursor: w-resize;}.ew-resize{cursor: ew-resize;}.ns-resize{cursor: ns-resize;}.nesw-resize{cursor: nesw-resize;}.nwse-resize{cursor: nwse-resize;}.col-resize{cursor: col-resize;}.row-resize{cursor: row-resize;}.zoom-in{cursor: zoom-in;}.zoom-out{cursor: zoom-out;}.grab{cursor: grab;}.grabbing{cursor: grabbing;}
    &lt;/style&gt;
    </head> <body>
    &lt;h2&gt;CSS cursor Property&lt;/h2&gt;
    &lt;div class="demo-cursor auto"&gt;
        &lt;h3&gt;Auto&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor default"&gt;
        &lt;h3&gt;Default&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor crosshair"&gt;
        &lt;h3&gt;Crosshair&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor pointer"&gt;
        &lt;h3&gt;Pointer&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor move"&gt;
        &lt;h3&gt;Move&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor text"&gt;
        &lt;h3&gt;Text&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor wait"&gt;
        &lt;h3&gt;Wait&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor help"&gt;
        &lt;h3&gt;Help&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor not-allowed"&gt;
        &lt;h3&gt;Not-allowed&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor progress"&gt;
        &lt;h3&gt;Progress&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor alias"&gt;
        &lt;h3&gt;Alias&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor copy"&gt;
        &lt;h3&gt;Copy&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor no-drop"&gt;
        &lt;h3&gt;No-drop&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor e-resize"&gt;
        &lt;h3&gt;e-resize&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor n-resize"&gt;
        &lt;h3&gt;n-resize&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor ne-resize"&gt;
        &lt;h3&gt;ne-resize&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor nw-resize"&gt;
        &lt;h3&gt;nw-resize&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor s-resize"&gt;
        &lt;h3&gt;s-resize&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor se-resize"&gt;
        &lt;h3&gt;se-resize&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor sw-resize"&gt;
        &lt;h3&gt;sw-resize&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor w-resize"&gt;
        &lt;h3&gt;w-resize&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor ew-resize"&gt;
        &lt;h3&gt;ew-resize&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor ns-resize"&gt;
        &lt;h3&gt;ns-resize&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor nesw-resize"&gt;
        &lt;h3&gt;nesw-resize&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor nwse-resize"&gt;
        &lt;h3&gt;nwse-resize&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor col-resize"&gt;
        &lt;h3&gt;col-resize&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor row-resize"&gt;
        &lt;h3&gt;row-resize&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor zoom-in"&gt;
        &lt;h3&gt;Zoom-in&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor zoom-out"&gt;
        &lt;h3&gt;Zoom-out&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor grab"&gt;
        &lt;h3&gt;Grab&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class="demo-cursor grabbing"&gt;
        &lt;h3&gt;Grabbing&lt;/h3&gt;
    &lt;/div&gt;
    </body> </html>
    Cursor Properties

    display

    CSS display controls how an element is displayed.

    display: none | block | inline | flex | grid | inline-block | inline-flex | inline-grid | table | inline-table | contents;

    float

    CSS float determines if an element floats to the left or right, allowing text to wrap around it or be displayed inline.

    float: none | left | right | initial | inherit;

    position

    CSS position sets the positioning model for an element.

    position: static | relative | absolute | fixed | sticky;

    visibility

    CSS visibility determines if an element is visible in the document.

    visibility: visible | hidden | collapse | initial | inherit;

    CSS Functions

    CSS functions can be used to add style and formatting to your website or application and can greatly improve the user experience.

    Follow the below list of functions types to know each one of them.

    Transform Functions

    CSS Transform Functions define how an element is visually transformed.

    transform: <transform-function> <transform-function>*;

    Common transform functions used in CSS are: rotate(), rotate3d(), scale(), scale3d(), skew(), translate(), and translate3d().

    Math Functions

    CSS Math Functions perform mathematical operations within CSS properties.

    property:calc(expression);

    Common transform functions used in CSS are: calc(), max(), min(), round() and trigonometric functions.

    Filter Functions

    CSS Filter Functions apply graphical effects like blur, brightness, and contrast.

    filter: none | blur() | brightness() | contrast() | drop-shadow() | grayscale() | hue-rotate() | invert() | opacity() | saturate() | sepia() | url();

    Color Functions

    CSS Color Functions define colors in multiple formats.

    color(colorspace c1 c2 c3[ / A])

    Image Functions

    CSS Image Functions generate images or gradients.

    <image> = <url> | <image-list> | <element-reference>  | <gradient></gradient>
    

    Counter Functions

    CSS Counter Functions work with the content property for automatic numbering.

    content:counter(name, style);

    Shape Functions

    CSS Shape Functions define clipping and shape effects.

    clip-path:circle(radius) | ellipse(rx ry) | polygon(x1 y1, x2 y2, ...);

    Reference Functions

    CSS Reference Functions allow referencing values defined elsewhere.

    property:var(--custom-property, fallback-value);

    Grid Functions

    CSS Grid Functions define grid layouts.

    grid-template-columns: none | auto | max-content | min-content | minmax() | length | percentage | fit-content() | repeat() | subgrid | initial | inherit;

    Font Functions

    CSS Font Functions control font rendering dynamically.

    font-variant-alternates: normal | stylistic(<feature>) || historical-forms || styleset(<feature>) || character-variant(<feature>) || swash(<feature>) || ornaments(<feature>) || annotation(<feature>);

    Easing Functions

    CSS Easing Functions control animation timing.

    transition-timing-function: ease | linear | ease-in | ease-out | ease-in-out | cubic-bezier(x1, y1, x2, y2);

    Note: To know in details about each function please check the article CSS Functions.

    Media Queries

    Media Queries allow to apply CSS styles to a webpage based on the characteristics of the device or browser viewing the page. With media queries, we can create designs that adapt to different screen sizes, resolutions, and orientations.

    • CSS Media Types
    • CSS Media Features

    CSS Media Types

    all: Suitable for all devices.

    print: Intended for paged, opaque material and for documents viewed on screen in print preview mode. Please consult the section on paged media.

    @media print{selector{css-property: value;}}

    screen: Intended primarily for color computer screens.

    @media screen{selector{css-property: value;}}

    CSS Media Features

    orientation: To check whether the device's screen or page is in a portrait or landscape orientation.

    @media (orientation: portrait){div{background: lightgreen;}}

    aspect-ratio: To check the aspect ratio of the viewport or the rendering surface.

    @media (max-aspect-ratio: 3/2){div{background:violet;}}

    display-mode: To check the display mode of a web-application.

    @media (display-mode: fullscreen){body{background-color: violet;color: white;}}

    overflow-block: To determine how the user device handles content that goes beyond the initial container's boundaries in a vertical direction.

    @media (overflow-block: paged){p{color: green;}}

    overflow-inline: To determine how the user device handles content that goes beyond the initial container's boundaries in a horizontal direction.

    @media (overflow-inline: scroll){p{color: blue;}}

    height: To determine the height of the viewport.

    @media (height: 150px){div{background:violet;}}

    width: To determine the width of the viewport.

    @media (width: 200px){div{background: pink;}}

    Conclusion

    Following this Cheat Sheet will keeps you revised on CSS, if your are new to CSS then we will recommend you to follow our free CSS Tutorial.

    You can check our other Cheat Sheets

    • HTML Cheat Sheet
    • C Language Cheat Sheet
  • Interview Questions

    CSS stands for Cascading Style Sheets and is used to define the visual appearance and layout of web pages. CSS was first introduced by Hkon Wium Lie in 1996 to separate content structure from presentation for making it easier to style web pages.

    In this article, I present a list of commonly asked questions in CSS from the interview experience of multiple candidates. These questions are categorized into three parts: beginner level, intermediate level, and advanced level. In my experience, interviewers hardly plan to ask any particular question during your interview, questions usually start with basic concepts of the subject, and later they continue based on how you answer. If you answer well, they may ask more advanced questions to test the depth of your knowledge.

    This article focuses only on interview-specific topics, so for a quick revision on all topics of CSS, check out the CSS quick guide and for a complete tutorial visit CSS tutorial.

    List of CSS Interview Questions and Answers

    • Basic CSS Questions And Answers For Beginners
    • Intermediate CSS Questions and Answers
    • Advanced CSS Interview Questions and Answers

    Basic CSS Questions And Answers For Beginners

    This section covers 20 basic CSS interview question along with their answers. Check out this section if you are absolute beginner to CSS.

    1. What is CSS?

    CSS stands for Cascading Style Sheets, is a language used to style and format the layout of web pages written in HTML. With CSS we can style webpage by changing color of the text, the style of fonts, the spacing between paragraphs, how columns are sized and laid out, what background images or colors are used.

    2. What are advantages of using CSS?

    Following are the advantages of using CSS.

    • Pages load faster: If you are using CSS, you do not need to write HTML tag attributes every time. Just write one CSS rule of a tag and apply it to all the occurrences of that tag. Since number of lines of code are reduced, our webpage will load faster.
    • Easy maintenance: To make a global change, simply change the root style, and all elements in all the web pages will be updated automatically.
    • Superior styles to HTML: CSS has a much wider array of attributes than HTML, so you can get a far better look to your HTML page.
    • Multiple Device Compatibility: For the same HTML document, different versions of a website can be presented for different screen widths
    • Global web standards: Now most of the HTML attributes are being deprecated and it is being recommended to use CSS.

    3. What are the drawbacks of CSS?

    Following are the drawbacks of using CSS.

    • Browser Compatibility: There are different levels of CSS i.e. CSS, CSS 2, CSS 3 which are often quite confusing. And these versions works differently on different browsers. Not all browsers support every CSS property in the same way.
    • Complexity with Large Projects: For large projects, managing CSS can become difficult. It may lead to redundant or conflicting styles if not organized well.
    • No Built-in Security: CSS does not offer security features. Hackers may view your CSS code and exploit vulnerabilities if they exist.
    • Global Scope: CSS rules apply globally by default, which can lead to unintended styling effects. We need to organize code well to avoid this.

    4. What is difference between CSS and CSS3?

    CSS3 is latest version of CSS. CSS3 have advanced features and functionalities. Following are the differences between features of CSS and CSS3.

    FeaturesCSSCSS3
    SelectorsCSS only has basic selectors, such as element, class, and ID selectors.CSS3 introduces advanced selectors like nth-child and attribute selectors for more precise targeting.
    Media QueriesMedia queries are not supported in CSS.CSS3 supports media queries for responsive design based on device properties like width and orientation.
    AnimationCSS doesnt have direct animation properties (JavaScript needed to apply animation)CSS3 includes properties like transition and animation to create animations without JavaScript.
    GradientsGradients are not directly supported in CSS.CSS3 supports gradients with the linear-gradient and radial-gradient properties.

    5. What is syntax for CSS Style?

    The syntax of CSS consist of selectors and declaration used to apply styles to HTML elements.

    selector{property: value;}
    • The selector targets the HTML element/elements that you want to style.
    • The declaration block contains one or more declarations enclosed in curly braces {}.
    • Each declaration consists of a property and a value separated by a colon :. Declarations are separated by semicolons ;.

    There are several types of selectors available in CSS, commonly used selectors are classes, IDs and tags. To know complete list of selectors visit our tutorial on CSS Selectors.

    6. How to add CSS to HTML page?

    There are three ways to add CSS styles to HTML webpage,

    • Internal CSS: In this case CSS codes are placed inside HTML files itself.
    • External CSS: A separate file is made for CSS and imported to HTML file.
    • Inline CSS: Styles for each tag can be exclusively provided using “style” attribute.

    To see example for each method, check out article CSS – How to add.

    7. Which type of CSS has the highest priority?

    In CSS, specificity determines the priority of styles. Inline CSS has the highest priority, followed by internal CSS, and then external CSS. To learn more, refer to CSS Specificity.

    8. What are selectors in CSS?

    CSS Selectors are used to select the HTML elements we want to style on a web page. They can target specific elements or groups of elements to apply styles like colors, fonts, margins, and more. Following are types of selectors in CSS.

    • Universal Selectors
    • Element Selectors
    • Class Selectors
    • Id Selectors
    • Attribute Selectors
    • Group Selectors
    • Pseudo-element Selectors
    • Pseudo-class Selectors
    • Descendant Selectors
    • Child Selectors
    • Adjacent Sibling Selectors
    • General Sibling Selectors

    9. What is universal selector?

    Universal selector, denoted by an asterisk mark (*), is a special selector that matches all elements in an HTML document. These are generally used to add a same length margin and padding to all the elements in document.

    *{color: #000000;}

    This rule sets color of every texts in webpage to black.

    10. What is class selector?

    A class selector targets an element with a specific value for its class attribute to style it. A class in CSS is denoted by “.” (period) symbol.

    .black{color: #000000;}

    This rule sets color of text inside all the elements having class as “.black” in the webpage to black color.

    11. What is an ID selector?

    An ID selector targets a specific element with a unique id attribute to style it individually. In CSS, an ID is represented by the “#” (hash) symbol.

    #main-heading{color: #333333;}

    This rule sets the text color of the element with the id “main-heading” to dark gray.

    12. What is an element selector?

    An element selector applies styles to all instances of a specific HTML element across the webpage. It uses the tag name directly without any symbols.

    p{font-size: 16px;}

    This rule sets the font size of all &lt;p&gt; (paragraph) elements to 16px.

    13. What is an Attribute Selector?

    An attribute selector in CSS targets elements based on the presence or value of a specific attribute. It is represented by square brackets around the attribute name.

    a[target="_blank"]{color: blue;text-decoration: underline;}

    This rule applies a blue color and underline style to all &lt;a&gt; elements with the attribute target="_blank", indicating links that open in a new tab.

    14. How to add comments in CSS?

    In CSS, comments can be added using /* */. Anything between /* and */ is treated as a comment and will not be rendered by the browser. Following is syntax to add comments in CSS.

    /* This is a comment */p{color: red;/* Set text color to red */}

    CSS comments are intended for the benefit of developers and are ignored by the browser when rendering a web page. They are useful in documentation, debugging, etc.

    15. How to set color in CSS?

    In CSS, the color property is used to set the text color for an element. You can specify colors in multiple formats, such as name, HEX, RGB, RGBA, HSL, and HSLA values.

    /* Examples of setting color */p{color: blue;/* Named color */color: #ff0000;/* HEX color */color:rgb(255, 0, 0);/* RGB color */color:rgba(255, 0, 0, 0.5);/* RGBA color with 50% opacity */color:hsl(0, 100%, 50%);/* HSL color */color:hsla(0, 100%, 50%, 0.5);/* HSLA color with 50% opacity */}
    • Named Colors: Set color using standard color names like red, blue, etc.
    • HEX Colors: Set color using a HEX code, e.g., #ff0000.
    • RGB Colors: Set color using RGB values, e.g., rgb(255, 0, 0).
    • RGBA Colors: Similar to RGB, but includes an alpha parameter for opacity, e.g., rgba(255, 0, 0, 0.5).
    • HSL Colors: Set color using HSL (Hue, Saturation, Lightness), e.g., hsl(0, 100%, 50%).
    • HSLA Colors: Similar to HSL, but with an alpha parameter, e.g., hsla(0, 100%, 50%, 0.5).

    15. What are CSS background properties?

    Background properties in CSS are used to control background graphics of HTML elements. We can set plain color, image, gradient for all the element HTML structure.

    • background-color: Used to define a solid background color for an element.
    • background-image: Used to set an image or a gradient as the background.
    • background-position: Used to specify the starting position of the background image .
    • background-size: Used to adjust the size of the background image.

    16. What are different CSS Border Properties?

    Border properties in CSS are used to control the appearance of borders around HTML elements. With these properties, we can set the color of border, style, width, and even apply rounded corners.

    • border-width: Specifies the width of the border, which can be in units like pixels, ems, or keywords such as thin, medium, or thick.
    • border-style: Defines the style of the border, such as solid, dashed, dotted, or none.
    • border-color: Sets the color of the border. It can be specified using color names, HEX codes, RGB, or HSL values.
    • border-radius: Specify roundness of corner of border.
    /* Example of border properties */.box{border-width: 2px;border-style: solid;border-color: #3498db;border-radius: 10px;}

    17. What is transition in CSS?

    CSS Transitions are used to smoothly change CSS properties over a specified time duration. Look at the example below.

    Without Transition

    With Transition

    Following code stimulate smooth transition of background color of button from lightblue to deepskyblue when user is hovered over the button.

    .button{background-color: lightblue;transition: background-color 0.3s ease;/* Smooth color change on hover */}.button:hover{background-color: deepskyblue;}

    18. How to hide an element in CSS

    We can hide an element in CSS by setting the display or visibility properties.

    • Using display: When you set an element’s display property to none, it is removed from the document flow, and the space it occupied is also removed.
    • Using visibility: Setting the visibility property to hidden makes the element invisible, but it still occupies space in the layout.
    /* The element will not be visible and won't take up space */.hidden{display: none;}/* The element will not be visible but will still take up space */.invisible{visibility: hidden;}

    19. Explain the difference between margin and padding

    Both margin and padding are used to create space around elements, but have different purposes. Margin is the space outside an element, creating distance between it and other elements, while padding is the space inside an element, ie the space between content and border of element. The following image shows padding and margin of an element in box model structure.

    Box model - Margin and padding differences

    Learn more with examples, CSS Margins and CSS Padding.

    20. Explain CSS box model

    CSS box model, as shown in image above is a layout concept that describes how elements are displayed on a webpage. This model treats each element as a rectangular box consisting of content, padding, border, and margin areas. we have two types of box model.

    • Standard box model: In this model content area of element is defined only from height and width of element. Padding, borders, and margins are added outside the content area. Following is code for standard box model.
    .box{width: 300px;height: 100px;padding: 20px;box-sizing: content-box;/* This is the default value */}

    Alternative box model: In this model, content area of element include height, width, padding, margin and border of element.

    .box{width: 300px;height: 150px;padding: 20px;box-sizing: border-box;/* Margin & padding included in content area */}

    Intermediate CSS Questions and Answers

    This section will cover 15 intermediate questions in CSS, which will cover key topics like advanced selectors, layout systems, animation, calc() function, media-queries, display inline block, specificity and responsive units.

    21. What are pseudo-class and pseudo-element selectors?

    Pseudo-classes in CSS are used to select and style elements based on their state or position within the document tree, without the need for adding extra classes or JavaScript. For example styling a button when mouse moves over or clicked on it.

    /* Example of Pseudo-class, Styling a link when mouse hovered*/a:hover{color: red;}

    pseudo-element in CSS, is used to style a specific part of an element that are not the part of the DOM (Document Object Model) and do not exist in the HTML markup. For Example first letter of a paragraph, placeholder text inside input element or selected part in a document.

    /* Example of pseudo-element, Styling first letter of a paragraph */p::first-letter{text-transform: uppercase;font-size: 2em;color: darkred;font-style: italic;}

    22. What are descendant and child selectors?

    Descendant Selectors in CSS are used to select elements that are nested within another element, no matter how deep the nesting is. They are represented by a space between the parent and child selectors. For example, if you want to style all paragraphs that are inside a div, you would write:

    /* Example of Descendant Selector */div p{color: blue;/* Affects all paragraphs inside any div */}

    Child Selectors only select elements that are directly nested within a parent element, and not consider deeper levels of nesting. This is represented by the > symbol. For instance, to style only the paragraphs that are directly inside a specific div, you would write:

    /* Example of Child Selector */div > p{color: green;/* Affects only the direct child paragraphs of a div */}

    23. What are adjacent sibling and general sibling selectors?

    Adjacent Sibling Selectors in CSS are used to select an element that is immediately next to a specific element, sharing the same parent. The adjacent sibling selector is represented by a plus sign (+). For example, if you want to select the first p element that immediately follows an h2 element, you would write:

    /* Example of Adjacent Sibling Selector */h2 + p{color: red;/* Affects only the first paragraph immediately after an h2 */}

    General Sibling Selectors select all elements that share the same parent, and come after a specific element, not necessarily immediately next to it. The general sibling selector is represented by a tilde (~). For instance, if you want to style all p elements that are siblings of an h2 element, you would write:

    /* Example of General Sibling Selector */h2 ~ p{color: purple;/* Affects all paragraphs that are siblings of h2 */}

    24. What is flexbox layout system? How to setup flex layout?

    Flexbox is a one-dimensional layout system in CSS that is used to arrange items inside container either horizontally or vertically. This system ensure responsive design using several properties for item sizing and alignment. The diagram shows flexbox layout in a container.

    Flexbox Example

    Designing flexbox systems is very simple. We just need to set display property of container as flex. Then we can use flex related properties to control alignment of items inside container. Following code shows an example of flex layout system.

    .container{display: flex;justify-content: space-between;/* Ensures Evenly spaced items */align-items: center;/* Centering items Vertically */}.item{background-color: lightcoral;padding: 20px;border: 3px solid #ccc;}

    25. Explain CSS grid layout and how to set it up?

    CSS Grid Layout is a two-dimensional layout system for developing responsive webpages. Grid Layout is ideal for creating overall structure of a webpage, while flexbox is mostly used to align items inside a container. Following image shows how a grid layout look like with 12 column structure.

    CSS Grid 12 Column

    To use the grid layout, set the container’s display property to grid. Then, we can define the number and size of rows and columns using properties like grid-template-rows and grid-template-columns. The following example code shows a basic grid layout.

    .container{display: grid;grid-template-columns:repeat(3, 1fr);/* Creates 3 columns */grid-template-rows: auto;/* Rows adjust based on content height */gap: 10px;/* Space between grid items */}.item{background-color: lightblue;padding: 20px;border: 2px solid #ddd;}

    26. How do you create an animation in CSS?

    We can setup animation in CSS using the @keyframes rules. The @keyframes rule define an animation by specifying how the animated element look at various stage of animation. Consider the following code that defines a keyframe rule.

    @keyframes colorChange{0%{background-color: red;}50%{background-color: green;}100%{background-color: blue;}}

    This keyframe rule is defined for an animation named colorChange.

    • At 0% of total duration of animation( ie, 0 seconds) the background color will be red.
    • At 50% of total time( ie, 2.5 seconds) the background color changes to green
    • At 100% of total duration( ie, 5 seconds) color changes to blue.

    Now, keyframes rules is defined. we can apply this to any element in webpage. Following code applies the animation to class ‘.box’.

    .box{animation: colorChange 5s infinite;}

    This code will define animation for element with class .box, the name of animation is colorChange, run for 5 seconds and it repeats infinite number of times.

    27. How do you use the calc() function in CSS?

    The calc() function in CSS is used to perform calculations directly within CSS properties. This function can add, subtract, multiply, or divide values, making it especially helpful for responsive designs where elements need flexible dimensions.

    /* Example using calc() to set width */div{width:calc(100% - 20px);/*Sets width as total width minus 20px*/}

    With calc(), you can mix different units (like px, %, and em) in a single calculation, which can be useful for layouts that need to adapt to various screen sizes.

    28. Explain how to use nth-child() selector in CSS

    The :nth-child(n) is a pseudo-class that will apply style to any specified direct child of an element.

    /* Syntax */tag:nth-child(number / expression / odd / even){property: value;}

    The pseudo-class nth-child can take number, mathematical expression or values like odd, even as parameter.

    • number: We can specify any number to this function, which represent chronological order of child elements, For example nth-child(4) will select 4th child of parent element.
    • odd/even: We can also use this function to select all odd/even occurrences of child element.
    • expression: We can provide any meaningful mathematical expression in terms of variable ‘n’ to this function. For example, nth-child(3n) will selects all the child occurring at multiple of 3.
    /* Examples *//* Apply Style to 2nd child of div */div:nth-child(2){background-color:red;}/* Apply Style to all odd children of li */li:nth-child(odd){background-color: lightgray;}/* Apply Style to 2n+1 th children, where n is 1, 2 ,3..., */li:nth-child(2n+1){background-color: lightblue;}

    29. How to center an element inside a container?

    Centering an element within a container can be done in several ways, depending on the layout and the type of centering needed. Here are some common methods:

    • Using Flexbox: Apply display: flex; and justify-content: center; and align-items: center; on the container to center the element both horizontally and vertically.
    .container{display: flex;justify-content: center;/* Horizontal Centering */align-items: center;/* Vertical Centering */height: 200px;}

    By setting above code for a container, the element inside the container will be centered. However, if you have multiple elements in the container, then you can use justify-content: space-around to provide even space around all element.

    • Using Margin Auto (Horizontal Centering): For block elements, you can use margin: auto; to center the element horizontally.
    /* Horizontal centering with margin auto */.element{width: 100px;height: 50px;background-color: lightgreen;margin: auto;}

    30. What is CSS media query? How is it working?

    Media queries in CSS are used to apply different CSS styles based on the screen size, resolution, and other characteristics of the user device. Media queries uses @media rule to include a extra block of CSS properties when a certain conditions are met. Media queries can also be used to style printable version of page separately.

    @media not|only mediatype and (media feature) and (media feature){
    
    CSS-Code;}</pre>

    Here, media-type can be things like screen, print, speech, etc., and media-feature can be characteristics such as width, height, aspect ratio, orientation, and more.

    /* Example *//* Style for screen size less than 500px */@media screen and (max-width: 500px){.container{flex-direction: column;/* Column layout on small screen */}}/* Styles for landscape orientation screen */@media (orientation: landscape){body{color: blue;}}

    31. How to style a webpage for printing?

    To style a page explicitly for printing, we have two methods:

    • Using External Stylesheet: We can have a external stylesheet explicitly for printing needs. For that we need to set the value for media attribute as "print" for link tag. Add the following tag to head section of your HTML document.
    <link href="/path/to/print.css" media="print" rel="stylesheet" />

    The print.css will look like this:

    body{background-color: white;color: black;}.navbar{display: none;}
    • Using Media Queries and @page: CSS media queries can be used to style printable versions in internal stylesheet itself. The @page rule is used to control aspects like the size, orientation, and margins of the printed content.
    @media print{body{background-color: white;color: black;}.navbar{display: none;}}@page{size: A4 portrait;/* A4 size, portrait orientation */margin: 2cm;/* 2cm margins on all sides */}

    32. What is CSS specificity? How to override specificity?

    The specificity order for selectors in CSS is a criteria to determine which selector have highest preference to be used for an element, when multiple selectors are specifying same property.

    specificity-order

    For instance, if a CSS property specified on an HTML element using both class selector and ID selector, the property declared in the selector with highest specificity value(in this case Id selector) will be applied on that element. Following are some rules for specificity in CSS.

    • The selector with highest specificity value will take effect.
    • For equal specificity value, latest rule wins.
    • Internal CSS style is always preferred over external stylesheet

    However, the order of specificity become irrelevant if any property is marked as !important. Which means, if any property in any selector is marked as important, then the property has highest preference regardless of selector used. Following code shows how to override specificity.

    #unique{color: darkgreen;/* This is ignored */}.special{color: blue !important;/* This will take effect */}
    
    <p id="unique" class="special"> This is paragraph </p>
    

    Check out chapter on !important rule to learn more.

    33. Explain the difference between inline, block, and inline-block elements.

    Inline, block and inline-block are values of CSS display property. Following table shows the difference between 'display: inline', 'display: block' and 'display: inline-block' properties.

    inlineblockinline-block
    The element is displayed on the same line.The element is displayed on a new line.The element is displayed on the same line .
    It does not take up the full width of the container.It takes up the full width of the container.It does not take up the full width of the container.
    It does not have a margin or padding by default.It has a margin and padding by default.It has a margin and padding by default.

    The below interactive section shows visual difference between this values.Display: Inline BlockDisplay: InlineDisplay: Block

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vesti bulum conseq. uat scel eris que elit sit amet consequat. Nullam cursus fermentum velit sed laoreet.

    34. What is difference between border and outline in CSS?

    In CSS, outlines are used to create line around the outside of an element's border, without impacting its size or layout. However, borders are used to create a visible separation between elements. Which means a border will takes up spaces in layout, but outlines won't take space in layout. Following image shows outline and border of an element.

    CSS Outlines and border
    • An outline does not take up space, which means an outline can overlap with adjacent elements if there is no enough margin. On the other hand, the border will never overlap with adjacent element.
    • Outline is always the same on all sides. But border can be varied on each side.
    • Outlines do not have to be rectangular because they follow the shape of the element to which they are applied.
    • Outlines are often used to highlight elements when they receive focus (by pressing tab or clicking). While borders are used to make visual separation between elements.

    Visit CSS outlines and CSS borders, to see examples and learn more.

    35. How do you style a visited link in CSS?

    To style a visited link in CSS, we can use the :visited pseudo-class, which targets links that the user has already clicked on. Heres an example.

    a:visited{color: purple;/* Change the text color */font-weight: bold;/* Make the link bold */}
    • For security reasons, visited link have limited styling options. Which means we cannot apply properties that reveal layout changes such as display, position to visited links.
    • Commonly allowed properties include color, background-color, text-decoration, and outline.

    36. What are responsive units? Why they are used?

    Responsive units are a set of special units used in CSS to describe measurements that can be scaled by the browser based on the viewport width or height. The most common responsive units are:

    • vw (viewport width): This unit is based on 1% of the viewport's width. For example, 10vw would equal 10% of the viewport's total width.
    • vh (viewport height): This unit is based on 1% of the viewport's height. For example, 50vh would be half the viewport's height.
    • vmin: This unit takes the smaller value between the viewport's width and height. Its helpful when you want the size to adapt to both portrait and landscape orientations.
    • vmax: This unit takes the larger value between the viewport's width and height, useful for designs that need to maximize space in larger viewports.

    Advanced CSS Interview Questions and Answers

    This section will cover 10 advanced questions in CSS, which include topics like clip path, import rule, custom properties, CSS cascade rule, counters, Houdini APIs, container queries, and critical CSS.

    37. Explain the clip-path property and its use cases

    The clip-path property in CSS is used to define a visible region of an element. This can be used to mask a certain portions of elements shape for creating visual effects. Following is syntax for clip-path property.

    clip-path: shape-function | URL | none;
    • shape-function: Defines a basic shape like a circle(), ellipse(), polygon(), or inset()
    • URL: Links to an SVG <clipPath> element for more complex clipping.
    • none: Remove all clippings, and make element completely visible.

    We can apply clip-path to images to give them custom shapes, such as circles, triangles, or polygons. This way we can display profile pictures as circles without using an actual circular image.

    /* Clips an element to circular path */clip-path:circle(50%);/*  Clips the element into an elliptical shape */clip-path:ellipse(50% 40%);/* Clips the element into a custom polygonal shape */clip-path:polygon(50% 0%, 100% 100%, 0% 100%);/* Clips the element by an inset rectangle */clip-path:inset(10% 20%);

    38. What is the @import rule in CSS, and how is it used?

    The @import rule in CSS is used to import external CSS files to stylesheets. This help us to separate CSS code across multiple files and then bring them together into a single stylesheet. Following is syntax of @import rule.

    /* Syntax */@import url("styles.css");
    • To avoid potential rendering issues, use @import at the beginning of stylesheet.
    • Each @import rule creates an additional HTTP request, which can slow down page load times. So, Inline <link> elements in HTML are usually preferred for better performance.
    • Performance issue doesnt occur in preprocessors like SASS, because files are combined into one before delivery.

    Suppose you have a main stylesheet, main.css, and want to import a reset file and a theme file. You could organize it like this:

    @import url("reset.css");@import url("theme.css");/* Additional styles */body{font-family: Arial, sans-serif;}

    39. What are custom properties in CSS? What is :root?

    Custom Properties are variables in CSS that are used to store and reuse values in stylesheet. These are same as variables in other programming languages. The :root pseudo-class is used to declare custom properties in CSS. We can also use any other selector to declare variables, but declaring in root: selector will give global access to the variable. The following code show how to declare and use custom properties in CSS.

    /* Declare custom properties */:root{--primary-color: #3498db;--font-size-large: 1.5rem;}/* Use custom properties */body{background-color:var(--primary-color);font-size:var(--font-size-large)}

    40. Explain the CSS cascade and how styles are applied.

    The CSS cascade is the process by which the browser determines which styles to apply when multiple rules could apply to the same element. CSS follows a specific order to resolve conflicts and decide which style to apply. This order includes:

    • !important tag: The styles, marked with !important, have the highest priority and override other styles.
    • Specificity: The browser checks how specific each selector is. ID selectors (#id) are more specific than class selectors (.class), which in turn are more specific than tag selectors (p, div).
    • Source Order: If two rules have the same importance and specificity, the rule defined last in the CSS will be applied.

    Every selectors in CSS have a specificity level, the cascading order is determined from this specificity order. Following are specificity order of CSS selectors.

    • Inline Styles: The styles defined for an element using style attribute have highest priority.
    • Id Selectors: In Selectors, id selector have highest priority.
    • Classes, Attributes and Pseudo-classes: These are the next in line. Class selectors are prefixed with a ., attribute selectors use square brackets [], and pseudo-classes are prefixed with :
    • Elements and Pseudo-elements: These have the lowest specificity. Element selectors use the element name directly, and pseudo-elements are prefixed with ::.

    Using the CSS cascade, styles are applied based on the combination of importance, specificity, and source order, allowing developers to control how elements are styled under various conditions.

    41. What are CSS counters, and how do you implement them?

    CSS counters are a kind of variables maintained by CSS, which can be incremented, decremented, or reset at different points in your document. For instance, we can use counters to automatically assign numbers to paragraphs, headings, and lists. Follow these steps to implement automatic counter for list items in a webpage

    • Initialize the Counter: To start using a counter, you first need to initialize it using the counter-reset property.
    body{counter-reset: section;}

    This code initializes a counter named section with an initial value of 0. The counter is reset to 0 every time the body element appears.

    • Increment the Counter: To increment the counter, use the counter-increment property.
    li::before{counter-increment: section;}

    This code increments the section counter every time an <li> element appears and displays the count before text.

    • Display the Counter: To display the value of the counter, use the counters() function.
    li::before{content:counters(section,".")" ";}

    This code displays the value of the section counter followed by a period and a space before the content of the li element.

    42. What are CSS Houdini and its APIs?

    CSS Houdini is a collection of low-level APIs that are used for creating custom styling, layout, and animation effects. With Houdini, developers can access the browser's CSS engine to define new properties and implement custom paint functions. Following are APIs in CSS Houdini.

    • CSS Properties and Values API: These APIs are used to define custom properties with specific types and default values. Also, these can be useful for creating custom styles that can respond to variable changes across your application.
    • Paint API (Paint Worklet): Used to create custom paint functions that can be used as background images or borders. It can generate complex patterns, gradients, or shapes directly in CSS without needing external images.
    • Animation Worklet: Used to create custom animations that respond to scrolling, user interaction, or time-based events. With this we can create complex animations.
    • Layout API: Used to create custom layout algorithms like masonry or grid layouts.
    • Typed OM: It provides a way to work with CSS values as structured data instead of plain strings.

    43. Explain CSS Paint API and CSS Animation API.

    The CSS Paint API and CSS Animation API are two of the key components of the CSS Houdini suite. They provide developers low-level access to extend and customize how CSS paints and animates elements.

    CSS Paint API (also known as the Paint Worklet) are used by developers to create custom graphics, patterns, and images programmatically with JavaScript, which can then be used as CSS backgrounds, borders, or other visual effects. The paint API uses a special JavaScript file that defines how to paint custom graphics. The worklet registers a paint function that the browser calls when it needs to render the graphic. Following code defines paint API using CSS and JavaScript.

    <!--Example: Creating a Striped Background with the Paint API--><!--JavaScript Code--><script>
    
    // Register a new paint worklet
    registerPaint('stripes', class {
    paint(ctx, size) {
        // Draw stripes pattern
        ctx.fillStyle = '#f06';
        for (let i = 0; i &lt; size.width; i += 20) {
        ctx.fillRect(i, 0, 10, size.height);
        }
    }
    });
    </script><!--CSS Implementation--><style>
    .element {
        background-image: paint(stripes);
    }
    </style>

    CSS Animation API are used by developers to create complex and highly customizable animations that can react to user interactions, scroll events, or any other dynamic conditions. This method allows precise control over animations at runtime, making it possible to create animations that respond to input in real-time. The Animation API uses an Animation Worklet where developers define animation logic.

    <!--Example: Creating a Scroll-Based Animation --><!--JavaScript Code--><script>
    // Register a new animator
    registerAnimator('scrollAnimator', class {
      animate(currentTime, effect) {
    
    effect.localTime = currentTime * 100; // Speed up the animation
    } }); </script><!--CSS Implementation--><style>
    .element {
        animation-timeline: paint(scrollAnimator);
        animation-name: scrollAnimation;
    }
    @keyframes scrollAnimation {
        from { transform: translateY(0); }
        to { transform: translateY(100px); }
    }  
    </style>

    44. Explain container queries and how they differ from media queries.

    Container Queries and Media Queries are two techniques used in CSS to apply styles based on certain conditions. Container queries in CSS is used to apply styles based on the size of a containing element. While Media queries are used to apply style based on size of viewport.

    • A container query can be defined using @container rule.
    • We need to set the property container-type: inline-size; to make an element container for triggering container queries.
    • Just like media queries, container queries listen to changes in the container's width, height, or other characteristics.

    Following is CSS code for container queries.

    /* Make a container */.container{container-type: inline-size;/* Defines the container */width: 100%;}/* Apply styles based on container size */@container (min-width: 500px){.box{background-color: lightblue;}}@container (min-width: 800px){.box{background-color: lightgreen;}}

    45. What is critical CSS and its importance.

    Critical CSS is a technique used to optimize website loading performance by separating and prioritizing the CSS needed to render above-the-fold content (the part of the page visible without scrolling) from the rest of the CSS.

    Here is how critical css works.

    • Identify Critical CSS: Determine which CSS rules are necessary to style the above-the-fold content.
    • Inline Critical CSS: Insert the critical CSS directly in the <head> section of the HTML document, so it loads immediately with the page.
    • Defer Non-Critical CSS: Load the remaining CSS (non-critical CSS) after the main content has been displayed, by linking to an external CSS file that loads asynchronously.

    Here is an example of using critical CSS in HTML document.

    <!DOCTYPE html><html lang="en"><head><title>My Website</title><style>
    
        /* Critical CSS inlined directly for faster rendering */
        body { 
            font-family: Arial, sans-serif; 
        }
        .header { 
            background-color: #333; 
            color: #fff; 
            padding: 10px; }
    &lt;/style&gt;&lt;link rel="stylesheet" href="styles.css" media="print" onload="this.media='all'"&gt;&lt;noscript&gt;&lt;link rel="stylesheet" href="styles.css"&gt;&lt;/noscript&gt;&lt;/head&gt;&lt;body&gt;&lt;div class="header"&gt;Welcome to My Website&lt;/div&gt;&lt;div class="main-content"&gt;This is the main content area.&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>