CSS Units define the measurement system used to specify the values. CSS offers a number of different units for expressing length and measurement. CSS unit is used to specify the property size for a page element or its content.
There are a number of ways to specify and measure length in CSS. It is used to specify margins, padding, font size, width, height, border, etc.
For example – font-size: 50px, here number 50 has a suffix px i.e., pixel, it is a CSS measurement unit.
There should be no whitespace between the number and the unit. The unit can be left out when the value is 0.
Length Units
Length units can be categorized into two types:
Absolute units: Fixed unit lengths that does not depend on screen width.
Relative units: Responsive unit lengths that changes according to screen width.
Absolute Length Units
These units are categorized as fixed-length units, which means that lengths specified with absolute units maintain an exact, unchanged size on the screen.
These units prove to be very effective when the browser has comprehensive information about the properties of the screen, the printer being used, or other appropriate user agents.Height: 2pxHeight: 2cmHeight: 2inHeight: 2pt
The following table contains all the types of absolute units:
Unit
Description
Equivalent value
Example
mm
Refers to millimeter, it is used to specify the measurements in millimeters.
1mm = 1/10th of 1cm
font-size: 10mm;
cm
Refers to centimeter, it is used to specify the measurements in centimeters.
1cm = 37.8px = 25.2/64in
font-size: 5cm;
Q
Refers to Quarter-millimeters, it is used to specify the measurements in centimeters.
1Q = 1/40th of 1cm
font-size: 5Q;
in
Refers to inches, it is used to specify the measurement in inches.
1in = 2.54cm = 96px
font-size: 1in;
pt
Refers to point, it is used to specify the measurements in points.
1pt = 1/72 of 1in
font-size: 20pt;
pc
Refers to picas, it is used to specify the measurement in picas.
1pc = 1/6th of 1in
width: 6pc;
px
Refers to pixels, it is used to specify the measurement in pixels.
1px = 1/96th of 1in
font-size: 15px;
Absolute units prove valuable for projects where responsiveness is not a priority. However, they are less beneficial for responsive websites because they do not adjust when screen dimensions change.
Example
Here is an example of absolute units (mm, cm, in, Q) used for font sizes:
Relative length units are measured in relation to other elements or viewport of the screen.
Relative units are great for styling responsive websites because they can be adjusted proportionally based on window size or parent elements. These units define lengths relative to other length properties.Height: 3emHeight: 3exHeight: 3lhHeight: 3vh
The following table contains all the types of relative units:
Unit
Description
Example
em
Relative to the font-size of the element.
font-size: 4em;
ex
Relative to the x-height of the current font.
font-size: 4ex;
ch
Relative to width of the "0".
font-size: 4ch;
rem
Relative to font-size of the root element.
font-size: 2rem;
lh
It is relative to the line height of the element.
font-size: 4lh;
rlh
It is relative to the line height of the root element.
font-size: 4rlh;
vh
It is relative to the height of the viewport. 1vh = 1% or 1/100 of the height of the viewport.
font-size: 4vh;
vw
It is relative to the width of the viewport. 1vw = 1% or 1/100 of the width of viewport.
width: 4vw;
vmin
It is relative to the smaller dimension of the viewport. 1vmin = 1% or 1/100 of the viewport's smaller dimension.
width: 4vmin;
vmax
It is relative to the larger dimension of the viewport. 1vmax = 1% or 1/100 of the viewport's larger dimension.
width: 4vmax;
vb
It is relative to the size of the initial containing block in the direction of the root element's block axis. 1vb = 1% of containing block's size (block axis).
font-size: 4vb;
vi
It is relative to the size of the initial containing block in the direction of the root element's inline axis. 1vb = 1% of containing block's size (inline axis).
font-size: 4vi;
svw, svh
It is relative to the width and height of the smaller viewport. 1svw = 1% or 1/100 of the smaller viewport's width and 1svh = 1% or 1/100 of the smaller viewport's height.
width: 40svw; height: 40svh;
lvw, lvh
It is relative to the width and height of the larger viewport. 1lvw = 1% or 1/100 of the larger viewport's width and 1lvh = 1% or 1/100 of the larger viewport's height.
width: 40lvw; height: 40lvh;
dvw, dvh
It is relative to the width and height of the dynamic viewport. 1dvw = 1% or 1/100 of the dynamic viewport's width and 1dvh = 1% or 1/100 of the dynamic viewport's height.
width: 40dvw; height: 40dvh;
Example
Here is an example of relative units (em, rem, vw, vh, %) used for font sizes:
Units px (Pixel) and em (indicates size relative to the size of the font) are two of the measurement units of length. In order to convert px to em, try our free CSS - PX to EM Converter.
The following table shows the 16 color names that were introduced in HTML 3.2, to support the 16 colors that 8-bit graphics cards offered. Same set of color can be used in CSS −
Color Name
Hex Value
Color
Show
aqua
#00ffff
Demo
black
#000000
Demo
blue
#0000ff
Demo
fuchsia
#ff00ff
Demo
green
#008000
Demo
gray
#808080
Demo
lime
#00ff00
Demo
maroon
#800000
Demo
navy
#000080
Demo
olive
#808000
Demo
purple
#800080
Demo
red
#ff0000
Demo
silver
#c0c0c0
Demo
teal
#008080
Demo
white
#ffffff
Demo
yellow
#ffff00
Demo
There are other colors, which are not part of HTML or XHTML but they are supported by most of the versions of IE or Netscape. These color names can be used in CSS as well.
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.