CSS Questions You Should Know
1. What is CSS?
Cascading Style Sheets (CSS) is a style sheet language used to describe the presentation of a document written in HTML or XML. It controls the layout, colors, fonts, and overall visual aesthetics of a webpage.
2. What is inheritance in CSS?
Inheritance is a mechanism by which properties are passed from a parent element to its children. Properties like color and font-family are inherited by default, while properties related to the box model (like margin, padding, and border) are not.
3. Explain specificity rules in CSS?
Specificity determines which CSS rule is applied when multiple rules target the exact same element. The hierarchy from highest to lowest is:
!importantdeclarations- Inline styles (
style="...") - ID selectors (
#id) - Classes, Attributes, and Pseudo-classes (
.class,[type="text"],:hover) - Elements and Pseudo-elements (
div,::before)
4. Explain 4 ways to import CSS in an HTML file.
- Inline CSS: Applied directly via the style attribute
<div style="color: red;"> - Internal CSS: Written inside a
<style>block within the<head>tag. - External CSS: Linked using
<link rel="stylesheet" href="styles.css">. - @import: Used inside a CSS file to import another CSS file
@import url("styles.css");
5. Can I use `<style>` tag in body instead of Head?
Technically, yes. Modern HTML5 allows <style> tags in the <body>, but it is heavily discouraged. Placing styles in the body causes a Flash of Unstyled Content (FOUC) because the browser has to re-calculate styles and re-paint the DOM mid-render.
6. Explain `!important`. Can we use `!important` in all CSS rules?
The !important flag overrides normal specificity rules, forcing a specific rule to take absolute precedence. While you can use it anywhere, you should avoid it. It breaks the natural cascade of CSS, making stylesheets incredibly difficult to debug and scale.
7. How can you center a div in a webpage, horizontally and vertically? Give 3 possible ways.
Method 1: Flexbox (Modern & Preferred)
.parent {
display: flex;
justify-content: center;
align-items: center;
}
Method 2: Grid
.parent {
display: grid;
place-items: center;
}
Method 3: Absolute Positioning
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
8. Explain positioning properties.
- static: The default behavior. The element flows naturally with the document.
- relative: Positioned relative to its normal
staticposition. - absolute: Positioned relative to the nearest positioned ancestor (an ancestor with a position other than static).
- fixed: Positioned relative to the viewport. It stays in place even when scrolled.
- sticky: Toggles between
relativeandfixeddepending on the user's scroll position.
9. What is the difference between sticky and fixed?
- Fixed elements are entirely removed from the document flow and locked to the viewport permanently.
- Sticky elements behave normally (
relative) until the user scrolls past a specified threshold (e.g.,top: 0), at which point they become "stuck" (fixed) inside their parent container.
10. What is difference between opacity:0, visibility:hidden, and display:none?
opacity: 0:The element is visually transparent, but it still takes up space in the layout and can still be clicked/interacted with.visibility: hidden:The element is invisible and cannot be clicked, but it still takes up space in the layout.display: none:The element is completely removed from the document flow. It takes up zero space and is invisible to screen readers.
11. How can I only make horizontal scroll, and disable vertical scroll?
.container {
overflow-x: auto; /* or scroll */
overflow-y: hidden;
}
12. Explain box model.
Every HTML element is essentially a rectangular box. The CSS Box Model consists of four distinct layers (from inside to outside):
- Content: The actual text or image.
- Padding: Transparent space surrounding the content, inside the border.
- Border: A visible line wrapping the padding and content.
- Margin: Transparent space outside the border, separating the element from others.
13. What does calc() function do?
The calc() function allows you to perform dynamic mathematical calculations (+, -, *, /) to determine CSS property values. It is exceptionally useful for mixing different units.
width: calc(100% - 50px);
14. Explain rem vs em.
- rem (root em): Relative to the font-size of the root
<html>element. It provides consistent sizing anywhere in the document. - em: Relative to the font-size of its direct parent element. It compounds, meaning nested
emelements can exponentially grow or shrink.
15. What is the default value of rem?
In almost all modern browsers, the default root font size is 16px. Therefore, 1rem = 16px by default.
16. Explain how I can change 1rem = 20px.
You can explicitly set the font-size on the html root tag:
html {
font-size: 20px; /* Now 1rem equals 20px globally */
}
Alternatively, you can use a percentage: font-size: 125%; (since 125% of 16px is 20px).
17. What are the benefits of using rem?
Using rem ensures scalable, accessible typography and spacing. Because rem respects the user's default browser font size, visually impaired users who increase their browser's base font size will automatically see your entire UI scale up proportionally without breaking the layout.
18. Explain clamp() function.
clamp(MIN, VAL, MAX) is a CSS function that restricts a value between a defined minimum and maximum boundary. It is heavily used for fluid, responsive typography.
/* Font size scales with viewport, but never drops below 1rem or exceeds 3rem */
font-size: clamp(1rem, 5vw, 3rem);
19. How can I show ... when some text is overflowing a container?
Use the text-overflow property combined with overflow and white-space:
.text-box {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
20. How can I restrict the number of lines using CSS?
You can use the -webkit-line-clamp property to truncate multi-line text:
.clamped-text {
display: -webkit-box;
-webkit-line-clamp: 3; /* Max number of lines */
-webkit-box-orient: vertical;
overflow: hidden;
}
21. How can I animate height width using CSS?
You can use the transition property combined with pseudo-classes like :hover:
.box {
width: 100px;
transition: width 0.3s ease-in-out;
}
.box:hover {
width: 200px;
}
(Note: Animating width/height triggers costly layout repaints. Whenever possible, prefer animating transform: scale() for better performance).
22. Rotate a div by 45 deg.
div {
transform: rotate(45deg);
}
23. Explain flex, and its properties.
Flexbox is a one-dimensional layout model used to align and distribute space among items in a container.
- Container Properties:
display: flex,flex-direction(row/column),justify-content(aligns along the main axis),align-items(aligns along the cross axis),flex-wrap. - Item Properties:
flex-grow(ability to grow),flex-shrink(ability to shrink),flex-basis(initial size).
24. How can I change the cursor using CSS?
Use the cursor property. Common values include pointer (hand icon), crosshair, not-allowed, grab, and wait.
button {
cursor: pointer;
}
25. How can I apply CSS to the first word of a paragraph using CSS?
CSS does not have a native pseudo-selector for the "first word" (it only has ::first-line and ::first-letter). To style the first word, you must manually wrap it in an inline HTML tag like a <span> and style that tag.
26. How can I check if user devices support hover or not, and based on that apply CSS?
You can use the interaction media query @media (hover: hover):
@media (hover: hover) {
.button:hover {
background-color: blue;
}
}
This ensures hover effects aren't awkwardly applied (or stuck) on mobile touch screens.
27. Explain sibling selectors.
- Adjacent Sibling Combinator (
+): Selects an element that is immediately following another element.h1 + ptargets only the first paragraph directly after an h1. - General Sibling Combinator (
~): Selects all elements that follow another element sharing the same parent.h1 ~ ptargets all paragraphs that come after an h1.
28. Explain clearfix property.
Clearfix is a legacy CSS hack used to solve a specific issue: when a container only contains floated (float: left/right) elements, its height collapses to zero. The clearfix forces the parent to expand and contain the floats:
.clearfix::after {
content: "";
display: table;
clear: both;
}
29. Explain how z-index works in CSS.
The z-index property controls the vertical stacking order of elements that overlap. Elements with a higher z-index value will render in front of elements with a lower value. Crucially, z-index only works on positioned elements (relative, absolute, fixed, or sticky).
30. What is the maximum number the z-index supports?
In modern browsers, z-index is stored as a 32-bit signed integer. Therefore, the maximum possible positive value is 2,147,483,647.
31. Explain background property.
The background property is a shorthand that allows you to set multiple background properties in a single line. It encompasses:
background-colorbackground-imagebackground-positionbackground-sizebackground-repeatbackground-attachment
32. What are different measurement units in CSS? Give at least 6 units.
- px (Pixels - Absolute)
- rem (Relative to root font-size)
- em (Relative to parent font-size)
- vw (Viewport Width - 1% of screen width)
- vh (Viewport Height - 1% of screen height)
- % (Percentage - Relative to parent element)
- ch (Character - Width of the "0" glyph)
33. Explain what does :has() do in CSS.
The :has() pseudo-class (often called the "parent selector") allows you to style an element based on the elements it contains inside it.
/* Styles a card ONLY if it contains an image */
.card:has(img) {
border: 2px solid blue;
}
34. What are vendor prefixes in CSS?
Vendor prefixes are identifiers added to experimental or non-standard CSS properties so that specific browsers can support them before they become an official standard. Examples include:
-webkit-(Chrome, Safari, newer Edge)-moz-(Firefox)-ms-(Internet Explorer)
35. How can you hide a scrollbar in CSS?
You can hide the scrollbar while still allowing the user to scroll:
/* Chrome, Edge, and Safari */
.container::-webkit-scrollbar {
display: none;
}
/* Firefox */
.container {
scrollbar-width: none;
}
36. What CSS properties you apply on a button which is disabled?
To visually and functionally disable a button, you typically use:
button:disabled {
opacity: 0.5;
cursor: not-allowed;
pointer-events: none; /* Prevents all click interactions */
}
37. What are pseudo elements?
Pseudo-elements are keywords appended to selectors that let you style specific, granular parts of an element without adding extra HTML markup. Common examples include ::before and ::after (to inject content), or ::first-letter and ::selection (styling highlighted text).
38. How can you give a border only to the left and right of a div?
You can explicitly target those sides using the specific border properties:
div {
border-left: 2px solid black;
border-right: 2px solid black;
}
39. Difference between outline and border.
- Border: Is part of the box model, meaning it takes up physical space and affects the layout and dimensions of the element.
- Outline: Is drawn outside the border. It takes up zero physical space and does not trigger layout shifts. It is heavily used for accessibility focus rings.
40. Explain margin padding collapsing feature.
Margin collapsing is a CSS behavior where the top and bottom margins of two adjacent (or parent/child) block-level elements touch and merge into a single margin. The size of the collapsed margin equals the largest of the two margins.
Note: Padding and horizontal margins never collapse.