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.
Function
Description
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.
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).
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
A 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.
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
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.
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.
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.
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;
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.
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.
Features
CSS
CSS3
Selectors
CSS 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 Queries
Media queries are not supported in CSS.
CSS3 supports media queries for responsive design based on device properties like width and orientation.
Animation
CSS doesnt have direct animation properties (JavaScript needed to apply animation)
CSS3 includes properties like transition and animation to create animations without JavaScript.
Gradients
Gradients 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 <p> (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.
This rule applies a blue color and underline style to all <a> 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.
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;}
A 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.
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.
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.
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.
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.
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.
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.
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.
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.
inline
block
inline-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.
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:
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.
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 < 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
@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.
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.
"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
<p>
Tutorialspoint - Simple and Easy Learning
</p></div><div class="col-sm-4"><h3>Column 2</h3><p>Tutorialspoint - Simple and Easy Learning</p><p>Tutorialspoint - Simple and Easy Learning</p></div><div class="col-sm-4"><h3>Column 3</h3><p>Tutorialspoint - Simple and Easy Learning</p><p>Tutorialspoint - Simple and Easy Learning</p></div></div></div></body></html></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.
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.
rel="stylesheet"></head><body><div class="container"><h1>Skeleton Framework</h1><p>Resize the screen to see responsive layout adjustments</p><div class="row"><div class="one-third column"><h3>Column 1</h3><p>Tutorialspoint - Simple and Easy Learning</p></div><div class="one-third column"><h3>Column 2</h3><p>Simple and Easy Learning</p></div><div class="one-third column"><h3>Column 3</h3><p>Tutorialspoint - Simple and Easy Learning</p></div></div></div></body></html></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.
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;
}
</style></head><body><p>
The video will cover 100% width
</p><video width="400" controls><source src="/css/foo.mp4" type="video/mp4"></video></body></html></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;
}
</style></head><body><p>
The video will cover 100% width if natural width is less than
output screen width
</p><video width="400" controls><source src="/css/foo.mp4" type="video/mp4"></video></body></html></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.
video {
max-width: 100%;
height: auto;
}
</style></head><body><div class="title"><h1>Responsive Web Design</h1></div><div class="grid-two"><ul><li>Viewport</li><li>Grid view</li><li>Media queries</li><li>Images</li><li>Videos</li><li>Frameworks</li></ul></div><div class="grid-one"><h1>Responsive Videos</h1><p>
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.
</p><video width="400" controls><source src="/css/foo.mp4" type="video/mp4"></video><p>
Resize the browser window to see how the content gets
responsive to the resizing.
</p></div></body></html></pre>
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;
}
</style></head><body><p>
The image will cover 100% width
</p><img src="/css/images/border.png"></body></html></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;
}
</style></head><body><p>
The image will cover 100% width if natural width is less than
output screen width
</p><img src="/css/images/border.png"></body></html></pre>
CSS Image Gallery
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.
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.
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;
}
}
Resize the browser window to see the background
color change.
</p><p><b> Note: </b>
If you can't resize here, Run in Tutorials point HTML compiler
</p></body></html></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;
}
}
Resize the browser window to see the background
color change.
</p><p><b> Note: </b>
If you can't resize here, Run in Tutorials point HTML compiler
</p></body></html></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;
}
}
</style></head><body><h3>Resize the browser window to see the effect.</h3><p>
The text color changed to blue when the viewport width is
at least 500px and the device is in landscape orientation.
</p><p><b> Note: </b>
If you can't resize here, Run in Tutorials point HTML compiler
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.
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.
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.
A 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.
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.
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;
}
</style></head><body><div class="container"><h1>Responsive Layout with Viewport Meta Tag</h1><div class="content"><p>
This layout adapts to the device screen width,
thanks to the viewport meta tag.
</p></div></div></body></html></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;
}
</style></head><body><div class="container"><h1>Non-Responsive Layout Without Viewport Meta Tag</h1><div class="content"><p>
This layout does not adapt to the device screen width,
because it lacks the viewport meta tag.
</p></div></div></body></html></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.
Responsive Web Design (RWD) is an approach of designing web applications that render accurately on various devices with different screen sizes and resolutions.
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.
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.