Blog

  • 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>
  • Frameworks

    CSS has various frameworks which are specialized in web development. These frameworks such as bootstrap, Tailwind CSS, and various more, have inbuilt classes and packages for commonly used UI components such as navigation bars, menu bars, buttons, image galleries, etc.

    In this chapter, we will learn and understand some of the most popular and freely available CSS frameworks for responsive web development.

    Responsive Web Designing Frameworks

    Here is a list of popular frameworks commonly used for responsive web designing.

    • Bootstrap
    • Tailwind CSS
    • Skeleton
    • Semantic UI

    Bootstrap Framework

    Bootstrap is a widely used open-source front-end framework used for creating responsive, mobile-first websites and web applications. Bootstrap provides a collection of CSS and JavaScript components, such as grids, forms, buttons, and navigation bars. These components can be easily implemented and customized. The common features of the bootstrap framework are mentioned below.

    Features For Responsive Design

    Here are some of the features of Bootstrap for responsive design.

    • Bootstrap provides a 12-column grid layout, making it easily adaptable to various screen sizes.
    • Bootstrap comes with utility classes. These utility classes help in applying margin, padding, and alignment adjustments for responsiveness.
    • Bootstrap includes responsive navigation, carousels, and models that adapt to screen sizes automatically.

    Example

    <!DOCTYPE html><html lang="en"><head><link href=
    "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" 
    
          rel="stylesheet"&gt;&lt;script src=
    "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script></head><body><div class="container-fluid p-5 bg-secondary text-white text-center"><h1>Bootstrap Framework</h1><p>Resize the screen to see the effect</p></div><div class="container mt-4"><div class="row"><div class="col-sm-4"><h2>Column 1</h2><p>
                Tutorialspoint - Simple and Easy Learning
            &lt;p&gt;  
                Tutorialspoint - Simple and Easy Learning
            &lt;/p&gt;&lt;/div&gt;&lt;div class="col-sm-4"&gt;&lt;h3&gt;Column 2&lt;/h3&gt;&lt;p&gt;Tutorialspoint - Simple and Easy Learning&lt;/p&gt;&lt;p&gt;Tutorialspoint - Simple and Easy Learning&lt;/p&gt;&lt;/div&gt;&lt;div class="col-sm-4"&gt;&lt;h3&gt;Column 3&lt;/h3&gt;&lt;p&gt;Tutorialspoint - Simple and Easy Learning&lt;/p&gt;&lt;p&gt;Tutorialspoint - Simple and Easy Learning&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Tailwind CSS

    Tailwind CSS is a utility-first CSS framework with lots of predefined classes. It has various customization options to design responsive web pages. With tailwind CSS, developers can style elements directly in the HTML. Tailwind supports purging unused CSS, which optimizes load times by removing unnecessary styles.

    Features For Responsive Design

    Here are some of the features of Tailwind CSS for responsive design.

    • Tailwind's utility classes provide precise control over design elements. It makes it easy to adjust the layout and manage spacing, and alignment based on screen size.
    • Tailwind is designed with a mobile-first approach i.e., developers can apply styles for smaller screens and can build up for larger screens.
    • Tailwind provides support for adding custom breakpoints. It offers flexibility in defining responsive behaviors designed to specific project needs.

    Example

    <!DOCTYPE html><html lang="en"><head><link href=
    "https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css" 
    
          rel="stylesheet"&gt;&lt;/head&gt;&lt;body class="bg-gray-100"&gt;&lt;div class="text-center py-10 bg-purple-600 text-white"&gt;&lt;h1 class="text-3xl font-bold"&gt;Tailwind CSS Framework&lt;/h1&gt;&lt;p class="text-lg"&gt;
            Resize the screen to see responsive behavior
        &lt;/p&gt;&lt;/div&gt;&lt;div class="container mx-auto mt-8"&gt;&lt;div class="grid grid-cols-1 md:grid-cols-3 gap-4"&gt;&lt;div class="bg-white p-6 rounded-lg shadow-md"&gt;&lt;h2 class="text-xl font-semibold"&gt;Column 1&lt;/h2&gt;&lt;p&gt;
                    Tutorialspoint - Simple and Easy Learning
                &lt;/p&gt;&lt;/div&gt;&lt;div class="bg-white p-6 rounded-lg shadow-md"&gt;&lt;h2 class="text-xl font-semibold"&gt;Column 2&lt;/h2&gt;&lt;p&gt;
                    Tutorialspoint - Simple and Easy Learning
                &lt;/p&gt;&lt;/div&gt;&lt;div class="bg-white p-6 rounded-lg shadow-md"&gt;&lt;h2 class="text-xl font-semibold"&gt;Column 3&lt;/h2&gt;&lt;p&gt;
                    Tutorialspoint - Simple and Easy Learning
                &lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Skeleton Framework

    Skeleton is a lightweight CSS framework that provides a basic structure for responsive web design. It focuses on simplicity and speed, making it ideal for small projects and quick prototypes.

    Features For Responsive Design

    • Skeleton's grid is based on a 12-column structure that adjusts accurately to fit different screen sizes.
    • Skeleton's smaller file size makes it fast-loading and easily customizable.
    • Skeleton includes responsive typography, forms, buttons, and other basic elements.

    Example

    Open Compiler

    <!DOCTYPE html><html lang="en"><head><link href=
    "https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" 
    
          rel="stylesheet"&gt;&lt;/head&gt;&lt;body&gt;&lt;div class="container"&gt;&lt;h1&gt;Skeleton Framework&lt;/h1&gt;&lt;p&gt;Resize the screen to see responsive layout adjustments&lt;/p&gt;&lt;div class="row"&gt;&lt;div class="one-third column"&gt;&lt;h3&gt;Column 1&lt;/h3&gt;&lt;p&gt;Tutorialspoint - Simple and Easy Learning&lt;/p&gt;&lt;/div&gt;&lt;div class="one-third column"&gt;&lt;h3&gt;Column 2&lt;/h3&gt;&lt;p&gt;Simple and Easy Learning&lt;/p&gt;&lt;/div&gt;&lt;div class="one-third column"&gt;&lt;h3&gt;Column 3&lt;/h3&gt;&lt;p&gt;Tutorialspoint - Simple and Easy Learning&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Semantic UI

    Semantic UI is a CSS framework that uses human-friendly HTML for creating responsive and visually appealing layouts. It includes a lot of libraries for themes and components. The common features of semantic UI are mentioned below.

    Features For Responsive Design

    Here are some of the features of semantic UI for responsive design.

    • Semantic UI includes a flexible grid that adjusts to various screen sizes.
    • It offers various responsive UI components such as buttons, forms, and menus.
    • It uses user-friendly HTML and Simple classes, making it easy to create responsive layouts.

    Example

    <!DOCTYPE html><html lang="en"><head><link href=
    "https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" 
    
          rel="stylesheet"&gt;&lt;/head&gt;&lt;body&gt;&lt;div class="ui container"&gt;&lt;h1 class="ui header"&gt;Semantic UI Framework&lt;/h1&gt;&lt;p&gt;Responsive design with Semantic UI&lt;/p&gt;&lt;div class="ui three column grid"&gt;&lt;div class="column"&gt;&lt;h3&gt;Column 1&lt;/h3&gt;&lt;p&gt;Tutorialspoint - Simple and Easy Learning&lt;/p&gt;&lt;/div&gt;&lt;div class="column"&gt;&lt;h3&gt;Column 2&lt;/h3&gt;&lt;p&gt;Simple and Easy Learning&lt;/p&gt;&lt;/div&gt;&lt;div class="column"&gt;&lt;h3&gt;Column 3&lt;/h3&gt;&lt;p&gt;Tutorialspoint - Simple and Easy Learning&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

  • Videos

    In responsive web design, its important to make sure videos are fitting properly to the layout. Videos should expand to fill the entire content area while keeping their original aspect ratio.

    When a fixed width or height of a video is specified, it may cause layout issue in very large or very small screens, such as breaking page layouts, distorting the shape, or displaying black bars around the video. The black bars around the video are called letterboxing (on top and bottom of the video), pillarboxing (on left and right of the video), and windowboxing (on all sides of the video).

    So, it’s important to use relative units for the width and height property such as percentage, instead of absolute values, such as pixels. Absolute values restrict the video getting responsive.

    Responsive Videos Using width Property

    To make an video scale according to screen size, we need to set width property of the video to 100% and height to auto.

    video{width: 100%;height: auto;}

    Setting style in this way makes the video take up 100% of the width of its parent element, and the height will be adjusted to maintain the video’s aspect ratio. This setup allows the video to scale with the screen size. However, on very large screens, the video may stretch beyond its natural width, making it appear distorted.

    Example

    In this example, the video displayed will scale according to screen size of output window. Run this code in Tutorialspoint HTML Compiler to adjust output window width and verify.

    <!DOCTYPE html><html><head><style>
    
        video {
            width: 100%;
            height: auto;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;
        The video will cover 100% width
    &lt;/p&gt;&lt;video width="400" controls&gt;&lt;source src="/css/foo.mp4" type="video/mp4"&gt;&lt;/video&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Responsive Videos Using max-width Property

    The above mentioned method has a drawback, on large screens the video will get stretched beyond it's natural dimension. To prevent this, we can use max-width property instead of 'width' property.

    video{max-width: 100%;height: auto;}

    By setting video properties in this way, the video will scale down if it has to, but never scale up to be larger than its original size.

    Example

    In this example, the video displayed will scale according to screen size of output window but never scale more than it's natural size. Run this code in Tutorialspoint HTML Compiler to adjust output window width and verify.

    <!DOCTYPE html><html><head><style>
    
        video {
            max-width: 100%;
            height: auto;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;
        The video will cover 100% width if natural width is less than
        output screen width
    &lt;/p&gt;&lt;video width="400" controls&gt;&lt;source src="/css/foo.mp4" type="video/mp4"&gt;&lt;/video&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Add a Video to the Example Web Page

    The following example demonstrates the use of a responsive video in a webpage. Based on the max-width value of the video, the video gets scaled down as per the screen size.

    Example

    <!DOCTYPE html><html><head><style>
    
    * {
        box-sizing: border-box;
    }
    .title {
        border: 2px solid black;
        padding: 10px;
        background-color: blanchedalmond;
    }
    .grid-one {
        width: 60%;
        float: left;
        padding: 10px;
        border: 2px solid black;
        background-color: darkseagreen;
    }
    .grid-two {
        width: 40%;
        float: left;
        padding: 15px;
        border: 2px solid black;
        background-color: lightgreen;
    }
    ul {
        list-style-type: none;
    }
    li {
        background-color: aqua;
        padding: 5px;
        border: 1px solid black;
        margin: 5px;
    }
    video {
        max-width: 100%;
        height: auto;
    }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div class="title"&gt;&lt;h1&gt;Responsive Web Design&lt;/h1&gt;&lt;/div&gt;&lt;div class="grid-two"&gt;&lt;ul&gt;&lt;li&gt;Viewport&lt;/li&gt;&lt;li&gt;Grid view&lt;/li&gt;&lt;li&gt;Media queries&lt;/li&gt;&lt;li&gt;Images&lt;/li&gt;&lt;li&gt;Videos&lt;/li&gt;&lt;li&gt;Frameworks&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;div class="grid-one"&gt;&lt;h1&gt;Responsive Videos&lt;/h1&gt;&lt;p&gt;
            Alike images, videos can be made responsive too, such 
            that the video should expand to fill the entire content 
            area, while maintaining its original aspect ratio.
        &lt;/p&gt;&lt;video width="400" controls&gt;&lt;source src="/css/foo.mp4" type="video/mp4"&gt;&lt;/video&gt;&lt;p&gt;
            Resize the browser window to see how the content gets 
            responsive to the resizing.
        &lt;/p&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

  • Images

    In responsive web design, its important to make sure images fit well on all screen sizes and resolutions. By using properties like max-width and min-width, images can automatically resize to fit different screens. In this chapter, well learn how to make images responsive, look at key properties for responsive images, and see how to create a responsive image gallery.

    When an image is uploaded to a webpage, it will be displayed in it’s default width and height. We can change these dimensions in CSS so that the image fits according to available space in our layout. One of the popular approach to set image dimension, is to keep a fixed width for image (such 50% of screen or 25% of screen) and height will be set automatically according to aspect ratio of the image.

    For better adaptability, we should always use relative units for the width property such as percentage, instead of absolute values, such as pixels. Absolute values restrict the image getting responsive.

    Responsive Image Using width Property

    To make an image scale according to screen size, we need to set width property of the image to 100% and height to auto.

    img{width: 100%;height: auto;}

    Setting style in this way makes the image take up 100% of the width of its parent element, and the height will be adjusted to maintain the image’s aspect ratio. This setup allows the image to scale with the screen size. However, on very large screens, the image may stretch beyond its natural width, making it appear distorted.

    Example

    In this example, the image displayed will scale according to screen size of output window. Run this code in Tutorialspoint HTML Compiler to adjust output window width and verify.

    <!DOCTYPE html><html><head><style>
    
        img {
            width: 100%;
            height: auto;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;
        The image will cover 100% width
    &lt;/p&gt;&lt;img src="/css/images/border.png"&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Responsive Image Using max-width Property

    The above mentioned method has a drawback, on large screens the image will get stretched beyond it's natural dimension. To prevent this, we can use max-width property instead of 'width' property.

    img{max-width: 100%;height: auto;}

    By setting image properties in this way, the image will scale down if it has to, but never scale up to be larger than its original size.

    Example

    In this example, the image displayed will scale according to screen size of output window but never scale more than it's natural size. Run this code in Tutorialspoint HTML Compiler to adjust output window width and verify.

    <!DOCTYPE html><html><head><style>
    
        img {
            max-width: 100%;
            height: auto;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;
        The image will cover 100% width if natural width is less than
        output screen width
    &lt;/p&gt;&lt;img src="/css/images/border.png"&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Image Gallery is used to organize and display multiple images in responsive and visually appealing format. CSS properties can be used to control the layout of images, size, shape, spacing, spanning and lot of other visual effects.

    CSS grid layout is most commonly used layout system for designing image gallery, with this we can align images in 2 dimensional manner.

    Example

    <!DOCTYPE html><html><head><style>
    
        /* Gallery container */
        .gallery {
            display: grid;
            gap: 10px;
            padding: 10px;
            font-family: Arial, sans-serif;
        }
        /* style image items */
        .gallery img {
            width: 100%;
            height: 100px; /* Set a same height for all images */
            object-fit: fit;
            display: block;
            border-radius: 8px;
            border: 3px solid #ccc;
            transition: all 0.3s ease;
        }
        /* Spanning the first image across two rows */
        .gallery img:first-child {
            grid-row: span 2;
            height: 210px; /* Double the height of regular images */
        }
        /* Spanning the sixth image across two columns */
        .gallery img:nth-child(6) {
            grid-column: span 2;
        }
        /* Hover effect */
        .gallery img:hover {
            transform: scale(1.02);
            border-color: #555 ; 
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div class="gallery"&gt;&lt;img src="/w3css/images/w3css_pdfcover.jpg" alt="Gallery Image 1"&gt;&lt;img src="/css/images/html.png" alt="Gallery Image 2"&gt;&lt;img src="/css/images/css.png" alt="Gallery Image 3"&gt;&lt;img src="/css/images/html.png" alt="Gallery Image 4"&gt;&lt;img src="/css/images/css.png" alt="Gallery Image 5"&gt;&lt;img src="/html/images/logo.png" alt="Gallery Image 6"&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    We can use CSS media queries to create a responsive image gallery that scales and rearranges its content based on the screen width. Following is simple media query that define number of column is image gallery for large screen and small screen.

    /* 4 columns in case of large screen */@media (min-width: 600px){.gallery{grid-template-columns:repeat(4, 1fr);}}/* 1 column in case of small screen */@media (max-width: 599px){.gallery{grid-template-columns: 1fr;}}

    With media queries we can also define style for specific orientation (landscape or portrait) of user device. The default value for this is portrait.

    Example

    This is example of designing a responsive image gallery.

    <!DOCTYPE html><html><head><style>
    
        /* Gallery container */
        .gallery {
            display: grid;
            gap: 10px;
            padding: 10px;
            font-family: Arial, sans-serif;
        }
        /* 4 columns in case of large screen */
        @media (min-width: 600px) {
            .gallery {
                grid-template-columns: repeat(4, 1fr);
            }
        }
        /* 1 column in case of small screen */
        @media (max-width: 599px) {
            .gallery {
                grid-template-columns: 1fr;
            }
        }
        /* Individual image items */
        .gallery img {
            width: 100%;
            height: 100px; /* Set a same height for all images */
            object-fit: fit; /* Ensure images fits the area */
            display: block;
            border-radius: 8px;
            border: 3px solid #ccc; /* Default border color */
            transition: all 0.3s ease;
        }
        /* Spanning the first image across two rows */
        .gallery img:first-child {
            grid-row: span 2;
            height: 210px; /* Double the height of regular images */
        }
        /* Spanning the sixth image across two columns */
        .gallery img:nth-child(6) {
            grid-column: span 2;
        }
        /* Hover effect */
        .gallery img:hover {
            transform: scale(1.02);
            border-color: #555 ; 
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div class="gallery"&gt;&lt;img src="/w3css/images/w3css_pdfcover.jpg" alt="Gallery Image 1"&gt;&lt;img src="/css/images/html.png" alt="Gallery Image 2"&gt;&lt;img src="/css/images/css.png" alt="Gallery Image 3"&gt;&lt;img src="/css/images/html.png" alt="Gallery Image 4"&gt;&lt;img src="/css/images/css.png" alt="Gallery Image 5"&gt;&lt;img src="/html/images/logo.png" alt="Gallery Image 6"&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>
  • Media Query

    In Responsive Web Designing, media queries rules are used to conditionally apply styles for specific screen widths, aspect ratios and resolutions. In this chapter, we will learn how to design a responsive web page using media query rule.

    What is Media Query?

    Media queries in CSS are used to apply different CSS styles based on the screen size, resolution, and other characteristics of the users device. Media queries use the @media rule to include an extra block of CSS properties when certain conditions are met.

    Adding a Breakpoint

    In responsive design, a breakpoint is a specific screen width where the layout changes to suit better to the screen size. We can add breakpoint by defining a media query with a maximum or minimum width. Following code shows the exact syntax.

    /* Example of a breakpoint for screens smaller than 768px */@media (max-width: 768px){.container{flex-direction: column;}}

    In this example, when the screen width is 768px or smaller, the .container layout changes to a column direction.

    Media Query Setting Width Limit

    We can set the width limit in media queries for applying styles only within specific screen width ranges. We define a minimum and a maximum width, to control the layout and appearance of elements within the desired screen size range.

    Example

    Here is an example, in which the body’s background color changes to plum when the viewport width is wider than 35em and narrower than 85em.

    <!DOCTYPE html><html><head><style>
    
    body {
        background-color: white; /* Default background */
    }
    @media (min-width: 35em) and (max-width: 85em) {
        body {
            background-color: plum; 
        }
    }
    </style></head><body><h1>Media Query Width Limit Example</h1><p>
        Resize the browser window to see the background 
        color change.
    &lt;/p&gt;&lt;p&gt;&lt;b&gt; Note: &lt;/b&gt;
        If you can't resize here, Run in Tutorials point HTML compiler
    &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Media Query Multiple Breakpoints

    We can use multiple breakpoints in media queries to design layout styling for different screen sizes, and condition of user devices. Let's understand this with an example.

    Example

    In this example, we have defined three breakpoints to adjust the font size and layout for small, medium, and large screens.

    <!DOCTYPE html><html><head><style>
    
    body {
        font-size: 16px; /* Default font size */
    }
    /* Small screens (up to 600px wide) */
    @media (max-width: 600px) {
        body {
            font-size: 14px;
        }
    }
    /* Medium screens (601px to 900px wide) */
    @media (min-width: 601px) and (max-width: 900px) {
        body {
            font-size: 16px;
        }
    }
    /* Large screens (901px and up) */
    @media (min-width: 901px) {
        body {
            font-size: 18px;
        }
    }
    </style></head><body><h1>Multiple Breakpoints Example</h1><p>
        Resize the browser window to see the background 
        color change.
    &lt;/p&gt;&lt;p&gt;&lt;b&gt; Note: &lt;/b&gt;
        If you can't resize here, Run in Tutorials point HTML compiler
    &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Media Queries For Screen Orientation

    We can define style for specific orientation (landscape or portrait) of user device. The default value for this is portrait.

    @media (orientation: portrait){/* Styles */}

    Example

    The following example demonstrates that when the screen width is greater than 500px and the device is in landscape orientation, the text color changes to blue.

    <!DOCTYPE html><html><head><style>
    
        body {
            color: red;
        }
        @media (min-width: 500px) and (orientation: landscape) {
            body {
                color: blue;
            }
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h3&gt;Resize the browser window to see the effect.&lt;/h3&gt;&lt;p&gt;
        The text color changed to blue when the viewport width is 
        at least 500px and the device is in landscape orientation.
    &lt;/p&gt;&lt;p&gt;&lt;b&gt; Note: &lt;/b&gt;
        If you can't resize here, Run in Tutorials point HTML compiler
    </p></body></html>
  • Grid view

    A responsive webpage always uses grid layout structure, as it can be easily adapted to different screen sizes and devices. In this chapter we will discuss grid view in responsive web development and how to design a grid based responsive website.

    What is Grid View?

    In responsive web design, a grid view is a layout structure that uses a grid-based system to arrange layout elements in rows and columns. A typical grid-view may have 12 columns, and has a total width of 100%. The grid will shrink and expand as the size of the browser changes.

    Building a Responsive Grid-View

    • Set Border Box: First of all we need to set box-sixing property as `border-box’ for all the elements in webpage. This will ensure padding and border are included in the total width and height of all elements. Use the following code to set:
    *{box-sizing: border-box;}

    Set Width of Column: Next we have to decide how many columns are needed in our webpage layout. For Example we need a 3 column layout, for that width of one column will be 100% / 3 columns = 33.33%.Use Media Queries: To ensure responsiveness, we have to use media queries for screen dependent stylings. With this we can add breakpoints for screen widths, at which layout need to be changed.

    Grid Rows and Columns

    In CSS, we can define the number of columns and rows required in our layout. Each cell will represent a grid item. Following code shows how to define rows and columns in grid.

    Example

    In this example we will create two grid layout one is for row and another one is for column, each grid has row and column.

    <!DOCTYPE html><html lang="en"><head><style>
    
        .grid-container {
            display: grid;
            gap: 10px;
            padding: 10px;
            width: 75%;
        }
        .grid-item {
            background-color: #4CAF50;
            border: 1px solid #ddd;
            padding: 20px;
            text-align: center;
            font-size: 1.2em;
            color: white;
        }
        .row{
            grid-template-columns: 1fr;
            grid-template-rows: repeat(3, 1fr);
        }
        .column{
            grid-template-columns: repeat(3, 1fr);
            grid-template-rows: 1fr;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;Grid Layout Example&lt;/h1&gt;&lt;h3&gt;Grid Rows&lt;/h3&gt;&lt;div class="grid-container row"&gt;&lt;div class="grid-item item1"&gt;
         Item 1
      &lt;/div&gt;&lt;div class="grid-item item2"&gt;
         Item 2
      &lt;/div&gt;&lt;div class="grid-item item3"&gt;
         Item 3
      &lt;/div&gt;&lt;/div&gt;&lt;h3&gt;Grid Columns&lt;/h3&gt;&lt;div class="grid-container column"&gt;&lt;div class="grid-item item1"&gt;
         Item 1
      &lt;/div&gt;&lt;div class="grid-item item2"&gt;
         Item 2
      &lt;/div&gt;&lt;div class="grid-item item3"&gt;
         Item 3
      &lt;/div&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Grid 12 Column Layout

    The 12 column layout structure involve dividing the container into 12 equal-width columns, So that each individual elements can span across a specified number of columns to create different sections. Following image shows an example of 12 column layout.

    12 column Layout example

    Example

    Following code shows example of designing a responsive 12 column layout. Run this in Tutorialspoint HTML Compiler to see how layout changes with width.

    <!DOCTYPE html><html lang="en"><head><title>12-Column Grid Layout</title><style>
    
        /* Basic Grid Container Styling */
        .grid-container {
            display: grid;
            grid-template-columns: repeat(12, 1fr); /* 12 equal-width columns */
            gap: 10px; /* Space between items */
            padding: 10px;
        }
        /* Column Spans */
        .col-span-12 {
            grid-column: span 12;
            background-color: #4CAF50;
            color: white;
            padding: 20px;
            text-align: center;
        }
        .col-span-8 {
            grid-column: span 8;
            background-color: #8BC34A;
            color: white;
            padding: 20px;
            text-align: center;
        }
        .col-span-4 {
            grid-column: span 4;
            background-color: #CDDC39;
            color: white;
            padding: 20px;
            text-align: center;
        }
        .col-span-3 {
            grid-column: span 3;
            background-color: #FFEB3B;
            color: black;
            padding: 20px;
            text-align: center;
        }
        /* Responsive Adjustments */
        @media (max-width: 400px) {
            .col-span-8, .col-span-4, .col-span-3 {
                grid-column: span 12; /* Make all elements full-width on smaller screens */
            }
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div class="grid-container"&gt;&lt;!-- Header --&gt;&lt;div class="col-span-12"&gt;Header (12 columns)&lt;/div&gt;&lt;!-- Main Content and Sidebar --&gt;&lt;div class="col-span-8"&gt;Main Content (8 columns)&lt;/div&gt;&lt;div class="col-span-4"&gt;Sidebar (4 columns)&lt;/div&gt;&lt;!-- Footer Links --&gt;&lt;div class="col-span-3"&gt;Footer Link 1 (3 columns)&lt;/div&gt;&lt;div class="col-span-3"&gt;Footer Link 2 (3 columns)&lt;/div&gt;&lt;div class="col-span-3"&gt;Footer Link 3 (3 columns)&lt;/div&gt;&lt;div class="col-span-3"&gt;Footer Link 4 (3 columns)&lt;/div&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

  • Viewport

    viewport, in the context of responsive web design, is a virtual area used by the browser to render a web page. The viewport is essential to web development and creation of responsive designs that adapt to various devices and screen sizes.

    What is a Viewport?

    Viewport is the visible area for a user in the web page. It will vary with the device, and will be smaller on a mobile phone than on a computer screen. On a desktop, the viewport is the window’s size, excluding the toolbar and other elements that are not the part of the web page. And on a mobile device, it is the size of the screen.

    Types of Viewport

    There are mainly two types of viewport, which are as follows:

    • Layout Viewport: It is the virtual area used by the browser to display the web page. The layout viewport is controlled by adding the meta viewport tag in the HTML head section.
    • Visual Viewport: It represents the part of the layout viewport that is currently visible on the screen. The visual viewport can be changed on zooming in and out.

    Both the viewports are mutable, which means, the dimensions of both can be altered after loading of the page.

    Setting The Viewport

    As mentioned above, we can control viewport width using <meta> tag. You should include the following <meta> viewport element inside head section of all your web pages for ensuring responsiveness.

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    In the above syntax, “content = width=device-width:” Set the width of the viewport same as the width of the device screen. And, “initial-scale = 1.0:” is used to set the initial zoom level to 100%.

    In the below section, we provided example of a web page without the viewport meta tag, and the same web page with the viewport meta tag.

    Example With Meta Tag

    The code below includes the viewport meta tag, which sets the layout viewport width equal to the device’s screen width. As a result, the page is responsive and adapts to different screen sizes.

    <!DOCTYPE html><html lang="en"><head><meta name="viewport" content="width=device-width, initial-scale=1"><style>
    
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
        }
        .container {
            width: 90%;
            background-color: lightblue;
            padding: 20px;
            text-align: center;
        }
        .content {
            width: 90%;
            margin: auto;
            background-color: lightcoral;
            padding: 10px;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div class="container"&gt;&lt;h1&gt;Responsive Layout with Viewport Meta Tag&lt;/h1&gt;&lt;div class="content"&gt;&lt;p&gt;
                This layout adapts to the device screen width, 
                thanks to the viewport meta tag.
            &lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example Without Viewport Meta Tag

    The code below does not include viewport meta tag, as a result the entire viewport will not be visible in smaller screens. A horizontally scroll option will appear on smaller screen reducing user experience.

    <!DOCTYPE html><html lang="en"><head><style>
    
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
        }
        .container {
            width: 100%;
            background-color: lightblue;
            padding: 20px;
            text-align: center;
        }
        .content {
            width: 90%;
            margin: auto;
            background-color: lightcoral;
            padding: 10px;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div class="container"&gt;&lt;h1&gt;Non-Responsive Layout Without Viewport Meta Tag&lt;/h1&gt;&lt;div class="content"&gt;&lt;p&gt;   
                This layout does not adapt to the device screen width, 
                because it lacks the viewport meta tag.
            &lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Units Related to Viewports

    In CSS, we can specify dimension of elements relative to viewport dimensions, such as to occupy 50% width of viewport or 100% height viewport. Following are popular units.

    • vw (viewport width): This unit is based on 1% of the viewport's width. For example, 'width: 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, 'height: 50vh' would be half the viewport's height.
    • vmin: This unit takes the smaller value between the viewport's width and height. It's 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.
  • RWD Introduction

    Responsive Web Design (RWD) is an approach of designing web applications that render accurately on various devices with different screen sizes and resolutions.

    Responsive structure

    What is Responsive Web Design?

    • Responsive web design ensure the webpage to look good in any user devices such as mobile, tablets, smart TVs and PCs.
    • To make a webpage responsive we can just use HTML and CSS. We don’t need to use programming languages like JavaScript.
    • CSS frameworks like bootstrap and tailwind CSS can simplify the process of making responsive designs.

    Example of Responsive Webpage

    Here is a complete example code explaining how to develop a simple responsive webpage using HTML and CSS. In the code given below, we have used media queries to define style for small screens.

    <!DOCTYPE html><html lang="en"><head><style>
    
        .grid-container {
            display: grid;
            grid-template-rows: 100px 200px 50px;
            grid-template-columns: 100px 1fr 1fr;
            grid-template-areas:
                "header header header"
                "sidebar content content"
                "footer footer footer";
            gap: 10px;
            background-color: lightgray;
            padding: 10px;
        }
        .grid-item {
            background-color: lightcoral;
            padding: 20px;
            text-align: center;
        }
        .header {
            grid-area: header;
        }
        .sidebar {
            grid-area: sidebar;
        }
        .content {
            grid-area: content;
        }
        .footer {
            grid-area: footer;
        }
        /* Responsive design for screens smaller than 768px */
        @media (max-width: 768px) {
            .grid-container {
                grid-template-columns: 1fr;
                grid-template-rows: auto;
                grid-template-areas:
                    "header"
                    "content"
                    "sidebar"
                    "footer";
            }
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div class="grid-container"&gt;&lt;div class="grid-item header"&gt;Header&lt;/div&gt;&lt;div class="grid-item sidebar"&gt;Sidebar&lt;/div&gt;&lt;div class="grid-item content"&gt;Content Area&lt;/div&gt;&lt;div class="grid-item footer"&gt;Footer&lt;/div&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    RWD Example

    Responsive Web Design Concepts

    We have mentioned below a list of concepts and techniques that are used in CSS for responsive web designing.

    • Media Queries: We use media queries to apply CSS rules based on device characteristics, such as screen width, height, or orientation (landscape or portrait). We can define different styles for different devices by using media queries.
    • Responsive Grid Layouts: We use responsive grid layouts, to alter the number of columns in layout dynamically based on dimensions of user devices. CSS frameworks such as Bootstrap, provide inbuilt grid systems that can automatically adjust the layout based on the screen size.
    • Responsive Images & Videos: To ensure images and videos are rendered properly in all user devices, we have to set a max-width property. It prevents stretching of media in large screens.
    • Viewport Meta Tag: The viewport meta tag is used in the HTML <head> section. It controls the viewport behavior and scale on mobile devices. It is important for proper rendering based on various screen sizes.