CSS Interview Questions and Answers

Find 100+ CSS interview questions and answers to assess candidates' skills in styling, selectors, layouts, animations, and responsive web design best practices.
By
WeCP Team

As modern web applications demand pixel-perfect, responsive, and accessible designs, Cascading Style Sheets (CSS) remain the backbone of front-end styling. Recruiters must identify developers who can write clean, scalable, and maintainable CSS to deliver seamless user experiences across devices and browsers.

This resource, "100+ CSS Interview Questions and Answers," is tailored for recruiters to simplify the evaluation process. It covers topics from CSS fundamentals to advanced design techniques, ensuring you can accurately gauge a candidate’s styling expertise.

Whether hiring for Front-End Developers, UI/UX Engineers, or Full-Stack Developers, this guide enables you to assess a candidate’s:

  • Core CSS Knowledge
    • Selectors & Specificity: Element, class, ID selectors, pseudo-classes/pseudo-elements, and the cascade.
    • Box Model: Margin, border, padding, and content flow.
    • Positioning & Layouts: Relative, absolute, fixed, sticky positioning, and display types.
    • Responsive Design: Media queries, fluid grids, and viewport-based units.
  • Advanced Skills
    • Flexbox & CSS Grid: Modern layout techniques for complex, responsive interfaces.
    • Transitions & Animations: Keyframes, easing functions, and hardware-accelerated animations.
    • Preprocessors & Architecture: SASS/SCSS, BEM methodology, and modular CSS for large projects.
    • Performance Optimization: Minimizing reflows/repaints, critical CSS, and browser rendering considerations.
    • Accessibility & Cross-Browser Compatibility: Ensuring styles work seamlessly across devices and meet WCAG standards.
  • Real-World Proficiency
    • Building scalable design systems and style guides.
    • Converting high-fidelity UI/UX designs into responsive, production-ready code.
    • Debugging layout issues with browser dev tools.
    • Integrating CSS with JavaScript frameworks like React, Vue, or Angular.

For a streamlined assessment process, consider platforms like WeCP, which allow you to:

Create customized CSS assessments tailored to your brand’s design requirements.
Include hands-on tasks, such as creating responsive layouts, implementing animations, or debugging cross-browser issues.
Proctor assessments remotely with AI-based integrity monitoring.
Leverage automated grading to evaluate code cleanliness, responsiveness, and adherence to best practices.

Save time, ensure visual consistency, and confidently hire CSS experts who can deliver elegant, maintainable, and high-performance interfaces from day one.

CSS Interview Questions and Answers

Beginner Level Question

  1. What is CSS?
  2. What are the different ways to apply CSS to a webpage?
  3. Explain the difference between class and id selectors.
  4. What is the box model in CSS?
  5. What is the difference between inline, block, and inline-block elements?
  6. What is the purpose of the z-index property in CSS?
  7. What does the float property do in CSS?
  8. How can you center a div horizontally and vertically in CSS?
  9. What are pseudo-classes in CSS? Give an example.
  10. What is the difference between absolute, relative, and fixed positioning?
  11. How do you create a responsive web page using CSS?
  12. What is the purpose of the clear property in CSS?
  13. Explain the display property in CSS.
  14. What is the difference between visibility: hidden; and display: none;?
  15. What are the different types of CSS selectors?
  16. What is the difference between the :hover and :focus pseudo-classes?
  17. How can you include an external CSS file in an HTML document?
  18. What is the use of @media queries in CSS?
  19. How do you create a CSS animation?
  20. What is the difference between the em, rem, px, vh, and vw units in CSS?
  21. How do you make a website mobile-friendly with CSS?
  22. What is a flexbox in CSS and how does it work?
  23. How would you style a hyperlink in its normal, visited, hover, and active states?
  24. What is the difference between padding and margin?
  25. What does the position: sticky; property do in CSS?
  26. What are inline and block level elements? Give examples of each.
  27. What is the difference between height and min-height in CSS?
  28. How can you style form elements (input fields, checkboxes, buttons) in CSS?
  29. What are font-size, font-family, and font-weight properties used for in CSS?
  30. What does the overflow property do in CSS?
  31. What is the difference between position: relative; and position: absolute;?
  32. How can you add a border to an element in CSS?
  33. What is the transition property in CSS used for?
  34. How do you style a list with bullets or numbers in CSS?
  35. What is a media query in CSS?
  36. What is the purpose of the !important rule in CSS?
  37. How can you create rounded corners in CSS?
  38. How do you add a background image to an element in CSS?
  39. What is the text-align property in CSS?
  40. What is the use of the opacity property in CSS?

Intermediate Level Question

  1. What is the flexbox layout, and how does it differ from grid?
  2. How do box-sizing: border-box; and box-sizing: content-box; differ?
  3. What are CSS preprocessors? Can you name a few popular ones?
  4. What is the calc() function in CSS? Provide an example of its use.
  5. How do you create a grid layout using CSS Grid?
  6. What are media queries, and how do they work in responsive design?
  7. How does position: fixed; behave differently than position: absolute;?
  8. What is a CSS reset, and why is it used?
  9. How do @import and link tags differ when importing CSS into an HTML document?
  10. Explain the concept of CSS specificity and how it affects the application of styles.
  11. What is the difference between opacity and rgba in CSS when setting colors?
  12. How do you achieve multi-column layouts in CSS?
  13. What is the difference between visibility and display in CSS?
  14. What are custom properties (CSS variables), and how do you use them?
  15. How can you create a responsive navigation bar using CSS?
  16. What are flex-direction, justify-content, and align-items in CSS Flexbox?
  17. What is the @keyframes rule in CSS, and how does it work?
  18. How would you implement a sticky header in CSS?
  19. What is the object-fit property in CSS used for?
  20. How do you create an image gallery using CSS Grid or Flexbox?
  21. What is the difference between rem and em units in CSS?
  22. How do you apply different styles based on device characteristics using @media queries?
  23. What are box shadows in CSS, and how are they applied?
  24. How would you implement a light/dark mode toggle button using CSS?
  25. What is the will-change property in CSS, and why is it important?
  26. How do you prevent text from overflowing its container in CSS?
  27. What are pseudo-elements in CSS? Give examples of ::before and ::after.
  28. How do you create a CSS animation that repeats indefinitely?
  29. What is the clamp() function in CSS, and how do you use it for responsive typography?
  30. What is the flex-wrap property in CSS Flexbox, and how does it work?
  31. How can you center a div using CSS Grid?
  32. What is the use of align-self in Flexbox?
  33. How can you make a container element fill the full height of the viewport using CSS?
  34. Explain the difference between border: solid; and border-style: solid;.
  35. What is the purpose of the visibility property in CSS, and how does it differ from display?
  36. How can you create a CSS-only dropdown menu?
  37. What are the advantages and disadvantages of using inline-block versus flexbox?
  38. How can you disable text selection on a webpage using CSS?
  39. What is the use of the clip-path property in CSS?
  40. What is the difference between transform and transition in CSS?

Experienced Level Question

  1. How does the will-change property help improve performance in CSS?
  2. What is the importance of the contain property in CSS?
  3. Can you explain CSS Grid's subgrid feature and provide an example?
  4. How does position: sticky; work and when is it used?
  5. What is the purpose of will-change: transform; in CSS animations?
  6. How do you implement a mobile-first approach in CSS?
  7. What are custom properties (CSS variables), and how do they differ from SASS variables?
  8. What are the performance considerations when using CSS animations and transitions?
  9. Explain how display: contents; works in CSS.
  10. How would you build a complex layout with CSS Grid and Flexbox?
  11. How does pointer-events work in CSS, and how can it be used to disable clicks on an element?
  12. What is the CSS rebeccapurple color and where did it originate from?
  13. How do you optimize CSS for faster page loads?
  14. What are object-fit and object-position, and how do they work in responsive design?
  15. Explain the concept of layout thrashing and how to avoid it in CSS.
  16. How does the position: relative; property influence the z-index of child elements?
  17. Can you explain the difference between display: flex; and display: inline-flex;?
  18. How do you manage cross-browser CSS compatibility issues?
  19. What is the mix-blend-mode property in CSS and how does it work?
  20. How do you use @supports in CSS to apply styles based on feature support?
  21. What are ch, vw, and vh units in CSS, and when should you use them?
  22. How do you optimize CSS for animations and transitions to prevent performance issues?
  23. What is the difference between flex and grid layout in CSS when handling complex layouts?
  24. How can you implement a CSS-only solution for a modal or popup window?
  25. How would you handle CSS for a component library or design system in large projects?
  26. What is the difference between CSS Grid and CSS Flexbox in terms of layout capabilities?
  27. How do CSS variables affect the maintainability of a project compared to traditional CSS?
  28. How would you create a complex 3D transformation effect in CSS?
  29. What is CSS Containment and how does it improve performance?
  30. How do you handle responsive typography across different devices using CSS?
  31. Explain how animation-timing-function works in CSS, and how would you use it to create custom easing curves?
  32. What is the purpose of backface-visibility in CSS and when should it be used?
  33. How would you implement a CSS Grid with dynamic rows and columns?
  34. What are the key differences between using absolute positioning and fixed positioning?
  35. How do you create a cross-browser compatible CSS modal window?
  36. What is text-overflow: ellipsis;, and how is it used?
  37. How can you achieve complex animations using @keyframes and transition in CSS?
  38. What is the visibility property in CSS used for, and when should it be used over display?
  39. How would you implement a CSS solution for a sticky footer in a page with dynamic content?
  40. How does CSS Grid and Flexbox handle responsive design differently, and which one should you choose for different use cases?

CSS Interview Questions and Answers

Beginners Question with Answers

1. What is CSS?

CSS (Cascading Style Sheets) is a stylesheet language that controls the visual presentation of a web page written in HTML or XML. Its primary role is to define the layout, colors, fonts, spacing, positioning, and other visual aspects of a webpage's content. Unlike HTML, which is used to structure the content, CSS is used to control the design, layout, and overall look and feel of the page.

The term "Cascading" refers to how styles are applied to elements. If multiple styles are applicable to the same element, CSS resolves them by applying styles in a cascading order, from the most specific to the least specific.

CSS is essential for web development as it allows developers to:

  • Create consistent styles across multiple web pages.
  • Separate content and design, making it easier to maintain and update the look of a website without altering the HTML structure.
  • Enhance user experience through animations, transitions, and responsive design.

CSS uses a rule-based syntax, where a selector is followed by a declaration block containing property-value pairs:

selector {
  property: value;
}

For example:

h1 {
  color: blue;
  font-size: 24px;
}

This rule will make all <h1> headers blue and set their font size to 24px.

2. What are the different ways to apply CSS to a webpage?

There are three primary ways to apply CSS to a webpage:

  1. Inline CSS:
    • Inline CSS is added directly to individual HTML elements using the style attribute. It's useful for small style changes or when styles need to be applied to specific elements, but it is generally considered bad practice for large-scale styling due to the lack of reusability and separation of concerns.
    • Example:
<p style="color: red; font-size: 20px;">This is an inline styled paragraph.</p>
  1. Internal CSS:
    • Internal CSS is defined within the <style> tag in the <head> section of the HTML document. It's ideal for applying styles to a single webpage, as it keeps the styles separate from the content while still being contained within the document.
    • Example:
<head>
  <style>
    p {
      color: blue;
      font-size: 16px;
    }
  </style>
</head>
  1. External CSS:
    • External CSS involves linking an external .css file to an HTML document using the <link> tag. This is the most efficient method for styling multiple pages, as the same stylesheet can be reused across different pages, reducing duplication and improving maintainability.
    • Example:
<head>
  <link rel="stylesheet" href="styles.css">
</head>
  1. External CSS is the most recommended method for large projects due to its reusability and separation of concerns (structure vs. design).

3. Explain the difference between class and id selectors.

Both class and id selectors are used in CSS to apply styles to HTML elements, but they have key differences in their usage and functionality:

  1. Class Selectors:
    • A class selector targets elements with a specific class attribute. It can be applied to multiple elements on the page, making it more flexible and reusable.
    • Class selectors are prefixed with a period (.) in CSS.
    • Example:
.button {
  background-color: blue;
  color: white;
}
<button class="button">Click me</button>
<div class="button">Another button</div>
  1. ID Selectors:
    • An ID selector targets a specific, unique element on the page. An ID should only be used once per page, which makes it more precise but less flexible than a class.
    • ID selectors are prefixed with a hash (#) in CSS.
    • Example:
#header {
  font-size: 24px;
  background-color: gray;
}
<div id="header">This is the header</div>

Key Differences:

  • Uniqueness: An ID should only be used once per page, while a class can be reused across multiple elements.
  • Specificity: An ID selector has a higher specificity than a class selector. This means if both a class and an ID selector target the same element, the ID’s styles will take precedence.

4. What is the box model in CSS?

The CSS Box Model is a concept that defines the structure and layout of elements in a webpage. It describes how each HTML element is rendered and the space it occupies, consisting of four main areas:

  1. Content: This is the actual content of the element, such as text or images. The width and height of the content box are defined by the width and height properties.
  2. Padding: Padding is the space between the content and the element's border. It is transparent and allows you to control the internal spacing around the content.
  3. Border: The border wraps around the padding (if any) and the content. It can be styled with properties such as border-width, border-style, and border-color.
  4. Margin: Margin is the space between the border and surrounding elements. It creates external spacing between elements.

When calculating the total width and height of an element, the box model is used as follows:

Total width = width + left padding + right padding + left border + right border + left margin + right margin
Total height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin

To avoid this "extra" space being included in the element's dimensions, you can use the box-sizing: border-box; property. This makes padding and borders part of the element's specified width and height.

5. What is the difference between inline, block, and inline-block elements?

The display property in CSS determines how an element behaves in the layout of a page. The three most common display types are:

  1. Block-level elements:
    • Block-level elements take up the full width of their container (default behavior), and they start on a new line, stacking vertically.
    • Examples: <div>, <p>, <section>, <header>.
    • These elements can have set width, height, margin, and padding.

Example

div {
  display: block;
  width: 100%;
}
  1. Inline elements:
    • Inline elements only take up as much width as necessary, and they do not cause line breaks. They flow along with the content in the same line.
    • Examples: <span>, <a>, <strong>.
    • These elements cannot have set width and height but can have padding and margin on the left and right sides.

Example:

span {
  display: inline;
}
  1. Inline-block elements:
    • Inline-block elements combine characteristics of both block and inline elements. Like inline elements, they do not cause line breaks. However, like block elements, they can have set width and height.
    • Examples: <button>, <input>, and other custom elements.
    • These elements are often used for creating flexible and responsive layouts.

Example:

.box {
  display: inline-block;
  width: 100px;
  height: 100px;
}

6. What is the purpose of the z-index property in CSS?

The z-index property in CSS controls the stacking order of positioned elements (those with position: relative, position: absolute, or position: fixed). It determines which elements appear in front of or behind other elements when they overlap. Elements with higher z-index values will appear on top of elements with lower z-index values.

  • Usage: To manipulate the visibility of overlapping elements, for example, placing modal windows or dropdown menus on top of other content.

Example:

.modal {
  position: absolute;
  z-index: 100;
}

.overlay {
  position: absolute;
  z-index: 50;
}

Here, the .modal will be displayed above the .overlay because its z-index is higher.

Note that z-index only works with elements that have a positioning context (i.e., elements with position set to something other than static).

7. What does the float property do in CSS?

The float property in CSS is used to position elements (usually images or text) to the left or right of their container, allowing content to wrap around them. It's primarily used for creating layouts, especially in older designs, but it has largely been replaced by more modern layout techniques like Flexbox and Grid.

  • float: left; — Moves the element to the left of its container.
  • float: right; — Moves the element to the right of its container.
  • float: none; — Removes the float (default value).

Example:

img {
  float: left;
  margin-right: 10px;
}

In this example, the image floats to the left, and the text will wrap around it. However, when using float, it's important to clear the float to prevent other elements from flowing around it unexpectedly.

8. How can you center a div horizontally and vertically in CSS?

Centering a <div> both horizontally and vertically is a common requirement in web design. Here are a few ways to do this using modern CSS techniques:

Using Flexbox: Flexbox provides a simple way to center elements both horizontally and vertically with minimal code:

.container {
  display: flex;
  justify-content: center;  /* Horizontally centers */
  align-items: center;      /* Vertically centers */
  height: 100vh;            /* Full viewport height */
}

Using Grid: CSS Grid also makes centering elements extremely easy:

.container {
  display: grid;
  place-items: center;  /* Shorthand for centering both horizontally and vertically */
  height: 100vh;
}

Using Absolute Positioning: If you want to use absolute positioning, you can center an element relative to its parent:

.container {
  position: relative;
  height: 100vh;
}
.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Flexbox and Grid are recommended for most use cases as they are more flexible and easier to maintain than traditional techniques like absolute positioning.

9. What are pseudo-classes in CSS? Give an example.

Pseudo-classes are special CSS selectors used to define the special states of an element. These selectors are prefixed with a colon (:) and target elements based on their state, position, or user interaction.

Some common pseudo-classes include:

  • :hover: Targets an element when the user hovers over it.
  • :focus: Applies when an element has focus (e.g., an input field).
  • :nth-child(): Selects elements based on their position in a parent container.
  • :first-child: Selects the first child of a parent element.
  • :last-child: Selects the last child of a parent element.

Example:

button:hover {
  background-color: green;
}

input:focus {
  border-color: blue;
}

In this example, the button's background color changes to green when hovered over, and the input field's border color changes to blue when focused.

10. What is the difference between absolute, relative, and fixed positioning?

In CSS, the position property specifies how an element is positioned within its container. The three main types of positioning are:

  1. Relative Positioning (position: relative;):
    • The element is positioned relative to its normal position in the document flow.
    • The top, left, right, and bottom properties move the element relative to where it would normally be.
    • The element still occupies space in the document.

Example:

.box {
  position: relative;
  top: 20px;
  left: 30px;
}
  1. Absolute Positioning (position: absolute;):
    • The element is positioned relative to its nearest positioned ancestor (i.e., any parent with a position other than static).
    • It is removed from the document flow and does not affect other elements.

Example:

.box {
  position: absolute;
  top: 50px;
  left: 100px;
}
  1. Fixed Positioning (position: fixed;):
    • The element is positioned relative to the viewport and stays in the same place even when the page is scrolled.
    • Fixed elements are often used for creating sticky headers or footers.

Example:

.box {
  position: fixed;
  top: 0;
  left: 0;
}

11. How do you create a responsive web page using CSS?

Creating a responsive web page ensures that your website looks good on devices of all screen sizes, from mobile phones to large desktop monitors. You can achieve responsiveness using CSS by utilizing flexible layouts, media queries, and fluid design elements. Here’s how:

  1. Use Relative Units:
    • Avoid fixed pixel widths for layout elements. Instead, use relative units like %, em, rem, vw, and vh, which scale with the viewport or the parent element.

Example:

.container {
  width: 80%;  /* 80% of the parent container's width */
}
  1. Flexbox:
    • Flexbox is a powerful layout model that allows elements to be flexible and responsive. It adjusts based on the screen size, making it great for designing responsive layouts.

Example:

.row {
  display: flex;
  flex-wrap: wrap;
}

.column {
  flex: 1 1 300px;  /* Each column takes up 1 part of available space, with a base width of 300px */
}
  1. CSS Grid:
    • CSS Grid allows for complex layouts and is very effective for creating responsive designs by automatically adjusting based on screen size.

Example:

.container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);  /* Create a 4-column layout */
}

@media (max-width: 768px) {
  .container {
    grid-template-columns: repeat(2, 1fr);  /* Change to 2 columns on smaller screens */
  }
}
  1. Media Queries:
    • Media queries are the cornerstone of responsive design. They allow you to apply different styles based on device characteristics such as width, height, resolution, and orientation.

Example:

@media (max-width: 768px) {
  .container {
    width: 100%;
  }
}

12. What is the purpose of the clear property in CSS?

The clear property in CSS is used to control the behavior of elements that follow floating elements. It ensures that elements are not wrapped around or aligned next to a floated element, but instead, they "clear" the float and appear below it.

  • Values:
    • clear: left; — Prevents an element from appearing next to a floating element on the left.
    • clear: right; — Prevents an element from appearing next to a floating element on the right.
    • clear: both; — Prevents an element from appearing next to a floating element on either side.
    • clear: none; — Default value, which allows the element to be placed next to the floated elements.

Example:

div {
  float: left;
  width: 200px;
}

p {
  clear: both;  /* The paragraph will appear below the floated div */
}

In this case, the paragraph <p> will not wrap around the floated <div> but will instead clear the float and move below it.

13. Explain the display property in CSS.

The display property in CSS specifies how an element should be rendered in the layout. It defines the behavior of an element in terms of box model and positioning. The most common values for display are:

  1. block:
    • Block-level elements take up the full width available, causing subsequent elements to start on a new line. Examples include <div>, <p>, and <section>.
    • Usage: Typically used for structural elements like containers, sections, and paragraphs.

Example:

div {
  display: block;
}
  1. inline:
    • Inline elements take up only as much width as necessary and do not cause a line break. Examples include <span>, <a>, and <strong>.
    • Usage: Applied to text or small elements that should not break the flow of content.

Example

span {
  display: inline;
}
  1. inline-block:
    • Combines properties of both block and inline elements. An element with display: inline-block; behaves like an inline element but allows for width and height to be set, like block elements.
    • Usage: Used for creating horizontal layouts or aligning elements while still maintaining control over their dimensions.

Example:

div {
  display: inline-block;
  width: 100px;
  height: 100px;
}
  1. none:
    • The none value removes the element from the document flow, making it invisible and causing it not to occupy any space on the page.
    • Usage: Often used to hide elements dynamically with JavaScript.

Example:

.hidden {
  display: none;
}

14. What is the difference between visibility: hidden; and display: none;?

Both visibility: hidden; and display: none; hide elements on the page, but they behave differently:

  1. visibility: hidden;:
    • The element is still in the document flow but is not visible. It still occupies space on the page and affects layout, but it’s invisible.
    • Use case: When you want to hide an element but maintain its layout space (e.g., for animations or transitions).

Example:

.hidden {
  visibility: hidden;
}
  1. display: none;:
    • The element is completely removed from the document flow, meaning it no longer takes up space or affects layout. It’s as if the element doesn't exist.
    • Use case: When you want to hide an element entirely and not affect the page layout.

Example:

.hidden {
  display: none;
}

Key Difference:

  • visibility: hidden; keeps the element’s space in the layout.
  • display: none; removes the element and its space from the layout.

15. What are the different types of CSS selectors?

CSS selectors target HTML elements to apply styles. Here are the most common types of selectors:

  1. Universal Selector (*):
    • Selects all elements on the page.
    • Example:
* {
  margin: 0;
  padding: 0;
}
  1. Element Selector:
    • Targets an HTML element by its name (e.g., <div>, <p>, etc.).
    • Example:
p {
  color: blue;
}
  1. Class Selector (.):
    • Selects elements with a specific class.
    • Example:
.my-class {
  font-size: 18px;
}
  1. ID Selector (#):
    • Selects an element with a specific id attribute.
    • Example:
Copy code
#my-id {
  color: red;
}
  1. Attribute Selector:
    • Selects elements with a specific attribute or attribute value.
    • Example:
input[type="text"] {
  background-color: yellow;
}
  1. Pseudo-class Selector:
    • Targets elements in a specific state (e.g., :hover, :focus, etc.).
    • Example:
a:hover {
  color: green;
}
  1. Pseudo-element Selector:
    • Selects part of an element (e.g., ::before, ::after).
    • Example:
p::before {
  content: "Note: ";
  font-weight: bold;
}
  1. Descendant Selector:
    • Selects elements that are inside another element.
    • Example:
.container p {
  font-size: 16px;
}

16. What is the difference between the and pseudo-classes?

The :hover and :focus pseudo-classes are used to target elements in specific states, but they serve different purposes:

  1. :hover:
    • Applies when the user hovers their cursor over an element.
    • Commonly used for interactive elements like links and buttons.
    • Use case: Change color, background, or add effects when the user hovers over a button or link.

Example:

a:hover {
  color: red;
}
  1. :focus:
    • Applies when an element receives focus (e.g., when a user clicks on or tabs into an input field).
    • Used primarily for form elements like input fields and buttons.
    • Use case: Change border or background color when the user focuses on an input field.

Example:

input:focus {
  border-color: blue;
}

Key Difference:

  • :hover is triggered by mouse interactions, while :focus is triggered when an element is selected or interacted with via keyboard or mouse.

17. How can you include an external CSS file in an HTML document?

To include an external CSS file in an HTML document, you use the <link> element in the <head> section of the document. The href attribute specifies the path to the CSS file.

Example:

<head>
  <link rel="stylesheet" href="styles.css">
</head>

This link points to the external styles.css file, which will apply styles to the HTML document.

18. What is the use of @media queries in CSS?

@media queries in CSS are used to apply styles based on specific conditions, such as screen width, resolution, or orientation. They enable responsive design, allowing you to tailor styles for different devices or screen sizes.

Syntax:

@media (condition) {
  /* CSS rules */
}

Example

@media (max-width: 768px) {
  .container {
    width: 100%;
  }
}

This media query applies styles when the viewport width is 768px or less (e.g., mobile devices). It's crucial for building responsive layouts.

19. How do you create a CSS animation?

CSS animations allow you to create dynamic changes in the state of an element over time. An animation is created using the @keyframes rule, which defines the intermediate steps of the animation.

  1. Define the animation with @keyframes:
    • @keyframes allows you to define the states (keyframes) of the animation.
  2. Apply the animation to an element:
    • Use the animation property to specify the animation's name, duration, and other settings.

Example:

@keyframes example {
  0% { background-color: red; }
  100% { background-color: blue; }
}

.box {
  width: 100px;
  height: 100px;
  background-color: red;
  animation: example 2s infinite;
}

In this example, the .box element changes from red to blue and back to red every 2 seconds, infinitely.

20. What is the difference between the em, rem, px, vh, and vw units in CSS?

These units are used to set sizes for elements, but each behaves differently:

  1. px (Pixels):
    • A fixed unit that represents one pixel on the screen. It is not relative to any other element and is not responsive.
    • Use case: Ideal for precise control over layout, but not ideal for responsive designs.
  2. em (Relative to parent element):
    • A relative unit based on the font size of the parent element. 1 em equals the current font size of the element.
    • Use case: Used for scalable and flexible layouts where font sizes and elements scale relative to their parent.

Example:

font-size: 2em;  /* 2 times the font size of the parent element */
  1. rem (Relative to root element):
    • Similar to em, but it is always relative to the root element’s font size (<html> element), typically set to 16px by default.
    • Use case: More predictable than em because it is always based on the root font size.

Example:

font-size: 1.5rem;  /* 1.5 times the root element's font size */
  1. vh (Viewport height):
    • Relative to 1% of the height of the viewport (the visible area of the web browser).
    • Use case: Used for full-screen layouts or setting the height of elements relative to the viewport height.

Example:

height: 50vh;  /* 50% of the viewport height */
  1. vw (Viewport width):
    • Relative to 1% of the width of the viewport.
    • Use case: Useful for setting element widths relative to the viewport.

Example:

width: 30vw;  /* 30% of the viewport width */

Key Differences:

  • px: Fixed, non-responsive.
  • em and rem: Scalable, with rem being more predictable than em.
  • vh and vw: Relative to the viewport dimensions.

21. How do you make a website mobile-friendly with CSS?

Making a website mobile-friendly involves using responsive design techniques that adapt the layout and content to different screen sizes. You can use the following strategies to ensure your website is mobile-friendly:

  1. Use Relative Units:
    • Instead of using fixed units like pixels (px), use relative units such as percentages (%), em, rem, vh, and vw to allow elements to resize dynamically based on the viewport size.

Example:

.container {
  width: 100%; /* Full width of the parent */
}
  1. Media Queries:
    • Media queries allow you to apply different CSS rules based on the viewport width (or other characteristics like device orientation). This helps create custom styles for smaller screens.

Example:

@media (max-width: 768px) {
  .container {
    padding: 10px;
  }
}
  1. Mobile-First Design:
    • Start by designing for small screens first (mobile-first), and then use media queries to scale the layout for larger screens. This is the opposite of the traditional desktop-first approach.
  2. Viewport Meta Tag:
    • In the <head> section of your HTML, include the viewport meta tag to control the scaling and sizing of the website on mobile devices.

Example:

<meta name="viewport" content="width=device-width, initial-scale=1.0">
  1. Flexible Layouts with Flexbox and Grid:
    • Use CSS Flexbox and Grid for flexible, responsive layouts that adjust to screen sizes.

Example (Flexbox):

.container {
  display: flex;
  flex-wrap: wrap;
}

.item {
  flex: 1 1 200px; /* Flex-grow, flex-shrink, and base width */
}

By combining these strategies, you can create a mobile-friendly, responsive website that adapts to various screen sizes and devices.

22. What is a flexbox in CSS and how does it work?

Flexbox (Flexible Box Layout) is a CSS layout model that allows you to design complex layouts with a simpler and more efficient approach compared to traditional models (like float or inline-block).

  • Flexbox container: The element with display: flex; or display: inline-flex; becomes the flex container, and its direct children are the flex items.
  • Main axis: The main axis is the direction in which the flex items are placed (by default, this is horizontal).
  • Cross axis: Perpendicular to the main axis, typically vertical.

Key properties:

  1. Flex container properties:
    • display: flex; — Enables the flex container.
    • justify-content — Aligns items along the main axis (e.g., center, space-between).
    • align-items — Aligns items along the cross axis (e.g., stretch, center).
    • flex-direction — Defines the direction of the flex items (row, column).
    • flex-wrap — Controls whether items should wrap onto multiple lines (wrap or nowrap).
  2. Flex item properties:
    • flex-grow — Determines how much the item should grow relative to other items.
    • flex-shrink — Defines how much the item should shrink relative to other items.
    • flex-basis — Specifies the initial size of the flex item before distributing space.

Example:

.container {
  display: flex;
  justify-content: space-between;  /* Distributes space between items */
}

.item {
  flex: 1 1 200px; /* Item will grow, shrink, and start at 200px */
}

23. How would you style a hyperlink in its normal, visited, hover, and active states?

You can use the following pseudo-classes to style hyperlinks in different states:

  • :link — Targets unvisited links.
  • :visited — Targets visited links.
  • :hover — Targets the link when hovered over.
  • :active — Targets the link when it’s being clicked.

Example:

a:link {
  color: blue;  /* Unvisited link color */
}

a:visited {
  color: purple;  /* Visited link color */
}

a:hover {
  color: red;  /* Hover effect */
  text-decoration: underline;
}

a:active {
  color: green;  /* Active (clicked) link color */
}

By using these pseudo-classes, you can provide visual feedback to users about the state of the link.

24. What is the difference between padding and margin?

Both padding and margin are used to create space around elements, but they differ in their function:

  • Padding:
    • Padding is the space between an element’s content and its border.
    • It increases the size of the element.
    • Padding is inside the element’s box.
    • Use case: To create space inside an element, making the content not touch the border.

Example:

.box {
  padding: 20px;
}
  • Margin:
    • Margin is the space between an element’s border and surrounding elements.
    • It does not affect the size of the element itself, but rather the spacing between elements.
    • Margin is outside the element’s box.
    • Use case: To create space between elements in a layout.

Example:

.box {
  margin: 20px;
}

Key difference: Padding adds space inside the element, while margin adds space outside the element.

25. What does the position: sticky; property do in CSS?

The position: sticky; property is a hybrid between relative and fixed positioning. It allows an element to behave like a relatively positioned element until it reaches a defined position in the viewport, at which point it "sticks" to that position and behaves like a fixed element.

  • Behavior: The element scrolls with the page until it reaches a specific offset from the viewport (e.g., from the top). Once the element reaches that point, it sticks in place until the containing block is out of view.

Example:

header {
  position: sticky;
  top: 0;  /* The header will stick to the top of the viewport */
  background-color: #fff;
  z-index: 100;
}

In this example, the header will scroll with the page until it reaches the top, at which point it will stick to the top of the viewport.

26. What are inline and block level elements? Give examples of each.

In HTML and CSS, elements can be categorized as inline or block-level based on their behavior in the layout:

  • Block-level elements:
    • Take up the full width of their container.
    • Always start on a new line (i.e., they are stacked vertically).
    • Examples: <div>, <p>, <header>, <footer>, <section>, <article>.

Example:

<div>This is a block-level element</div>
<div>This is another block-level element</div>
  • Inline elements:
    • Take up only as much width as necessary (they do not create new lines).
    • They are laid out within the same line, next to other inline elements.
    • Examples: <span>, <a>, <strong>, <em>.

Example:

<span>This is an inline element</span>
<span>This is another inline element</span>

27. What is the difference between height and min-height in CSS?

  • height:
    • Specifies the exact height of an element.
    • If the content inside the element exceeds this height, it will overflow (unless overflow properties are specified).
    • Use case: When you need to set a fixed height for an element.

Example:

.box {
  height: 200px;
}
  • min-height:
    • Specifies the minimum height of an element. The element can grow taller than the value set for min-height if the content inside it exceeds the minimum height.
    • Use case: When you want to ensure that an element is at least a certain height, but it can expand if needed.

Example:

.box {
  min-height: 200px;
}

Key difference: height sets a fixed height, while min-height allows flexibility for content to expand the element's height.

28. How can you style form elements (input fields, checkboxes, buttons) in CSS?

Form elements like input fields, checkboxes, and buttons can be styled using CSS. However, some elements have limited styling capabilities, especially on older browsers or in certain operating systems, due to default styles imposed by the browser.

Here are some ways to style them:

Input Fields:

input[type="text"] {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 16px;
}

input[type="text"]:focus {
  border-color: blue;
}
  1. Checkboxes:
    • You can use custom styles to hide the default checkbox and replace it with a custom design.
input[type="checkbox"] {
  width: 20px;
  height: 20px;
  margin-right: 10px;
}

Buttons:

button {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}

29. What are font-size, font-family, and font-weight properties used for in CSS?

  • font-size:
    • Specifies the size of the font.
    • Values can be in px, em, rem, vw, %, etc.

Example

p {
  font-size: 16px;
}
  • font-family:
    • Defines the font to be used for text in an element. You can specify multiple fonts as fallbacks in case the first font is not available.
    • Example:
body {
  font-family: "Arial", sans-serif;
}
  • font-weight:
    • Specifies the weight (boldness) of the font. Common values include normal, bold, and numeric values (100, 200, ..., 900).

Example:

h1 {
  font-weight: bold;
}

30. What does the overflow property do in CSS?

The overflow property controls what happens when content overflows an element’s box. It can be used to manage content that exceeds the element's size:

  • overflow: visible;: The content is not clipped and will overflow outside the element (default value).
  • overflow: hidden;: The overflowing content is clipped, and no scrollbars are provided.
  • overflow: scroll;: The content is clipped, but scrollbars are always displayed, even if the content does not overflow.
  • overflow: auto;: Scrollbars are displayed only when necessary (when the content overflows).

Example:

div {
  overflow: auto;
  width: 200px;
  height: 100px;
}

This will create scrollbars only if the content exceeds the dimensions of the element.

31. What is the difference between position: relative; and position: absolute;?

Both position: relative; and position: absolute; are used for positioning elements, but they behave differently:

  • position: relative;:
    • The element is positioned relative to its normal position in the document flow.
    • You can move the element from its original position using the top, right, bottom, or left properties, but it still occupies space in the document layout.
    • Use case: When you want to shift an element without affecting the layout of surrounding elements.

Example:

.relative {
  position: relative;
  top: 10px;
  left: 20px;
}
  • position: absolute;:
    • The element is positioned relative to its closest positioned ancestor (an ancestor with position set to relative, absolute, or fixed). If there’s no such ancestor, it is positioned relative to the initial containing block (usually the <html> element).
    • It is removed from the normal document flow, meaning it does not occupy space in the layout.
    • Use case: When you need to place an element in a specific location within a container or on the page, and you don’t want it to affect the layout.

Example:

.absolute {
  position: absolute;
  top: 20px;
  left: 30px;
}

32. How can you add a border to an element in CSS?

To add a border to an element, you can use the border property in CSS, which allows you to define the width, style, and color of the border.

Syntax:

element {
  border: <border-width> <border-style> <border-color>;
}
  • border-width: Specifies the thickness of the border.
  • border-style: Defines the style of the border (e.g., solid, dashed, dotted).
  • border-color: Specifies the color of the border.

Example:

div {
  border: 2px solid black;
}

This will create a black, solid, 2px wide border around the div element.

33. What is the transition property in CSS used for?

The transition property in CSS allows you to change property values smoothly (over a specified duration) when an element's state changes. It is most commonly used for animating CSS properties when an element is hovered, focused, or otherwise interacted with.

Syntax:

element {
  transition: <property> <duration> <timing-function> <delay>;
}
  • property: The CSS property to be transitioned (e.g., background-color, width, opacity).
  • duration: The time it takes for the transition to complete (e.g., 1s, 500ms).
  • timing-function: Controls the speed curve of the transition (e.g., linear, ease, ease-in).
  • delay: Specifies a delay before the transition starts (e.g., 0s, 1s).

Example:

button {
  background-color: blue;
  transition: background-color 0.5s ease;
}

button:hover {
  background-color: red;
}

In this example, when the button is hovered, the background color transitions smoothly from blue to red over 0.5 seconds.

34. How do you style a list with bullets or numbers in CSS?

To style an unordered list (bulleted list) or ordered list (numbered list), you use the list-style-type property in CSS:

  • list-style-type: Specifies the type of list item marker (bullet or number).
    • For unordered lists, the default marker is a bullet (disc), but you can change it to other types like circles or squares.
    • For ordered lists, the default is a number (decimal), but you can change it to letters or Roman numerals.

Example (Unordered List):

ul {
  list-style-type: square;  /* Changes bullet to square */
}

Example (Ordered List):

ol {
  list-style-type: upper-alpha;  /* Uses letters (A, B, C, ...) for numbering */
}

To remove the default bullets or numbers entirely, you can use list-style-type: none;:

ul {
  list-style-type: none;  /* Removes bullets */
}

35. What is a media query in CSS?

A media query in CSS is used to apply different styles based on the characteristics of the device or display, such as its width, height, resolution, or orientation. Media queries enable responsive web design, allowing styles to adapt to different screen sizes or devices.

Syntax:

@media (condition) {
  /* CSS rules */
}

Example:

@media (max-width: 768px) {
  body {
    background-color: lightblue;
  }
}

In this example, the background color will change to lightblue when the viewport width is 768px or less, typically on mobile devices.

36. What is the purpose of the !important rule in CSS?

The !important rule in CSS is used to give a specific style property higher priority over other conflicting styles. When you append !important to a CSS rule, it overrides other rules that would normally take precedence based on specificity or cascading order.

Example:

h1 {
  color: red !important;
}

In this example, the text color of <h1> elements will always be red, regardless of other conflicting styles in the CSS unless they also use !important.

Caution: While !important can be useful for overriding styles, it should be used sparingly. Overusing it can make your CSS harder to maintain and debug.

37. How can you create rounded corners in CSS?

You can create rounded corners on an element using the border-radius property. This property can apply a rounded effect to one or more corners of the element.

Syntax:

element {
  border-radius: <value>;
}
  • The <value> can be a length (e.g., px, em) or a percentage (%). If you specify a percentage, the corner will be rounded relative to the size of the element.

Example:

div {
  border-radius: 10px;  /* Applies rounded corners with 10px radius to all corners */
}

To create fully rounded circles (e.g., for buttons or images), use border-radius: 50%;:

img {
  border-radius: 50%;  /* Makes the image circular */
}

38. How do you add a background image to an element in CSS?

You can add a background image to an element using the background-image property in CSS. You can also control other background properties like background-size, background-repeat, and background-position for further customization.

Syntax:

element {
  background-image: url('image-url');
}

Example:

div {
  background-image: url('background.jpg');
  background-size: cover;  /* Ensures the image covers the whole element */
  background-position: center center;  /* Centers the image */
}

In this example, background-size: cover; ensures the image covers the entire element, and background-position: center center; centers the image within the element.

39. What is the text-align property in CSS?

The text-align property in CSS is used to control the horizontal alignment of text and inline elements within a block-level element.

Values:

  • left: Aligns text to the left.
  • right: Aligns text to the right.
  • center: Centers the text.
  • justify: Justifies the text (spreads it to align both left and right edges).

Example:

p {
  text-align: center;  /* Centers the text inside the <p> element */
}

In this example, the text inside the <p> tag will be centered.

40. What is the use of the opacity property in CSS?

The opacity property in CSS is used to control the transparency level of an element. The value can range from 0 (completely transparent) to 1 (completely opaque). You can also use decimal values (e.g., 0.5 for 50% opacity).

Syntax:

element {
  opacity: <value>;
}

Example:

div {
  opacity: 0.5;  /* Makes the element 50% transparent */
}

In this example, the div element will be semi-transparent, allowing the background or content behind it to be partially visible.

Intermediate Question and Answers

1. What is the Flexbox layout, and how does it differ from Grid?

Flexbox Layout:

  • The Flexbox (Flexible Box Layout) is a one-dimensional layout system designed to distribute space along a single axis (either horizontally or vertically). It allows you to align and distribute space between items in a container with great flexibility.
  • It works by defining a flex container and flex items within that container. The flex container distributes space among its flex items, allowing them to resize and align based on the available space.

Key Properties of Flexbox:

  • display: flex; — Defines the flex container.
  • flex-direction — Defines the direction of the items (row, column, etc.).
  • justify-content — Aligns items along the main axis.
  • align-items — Aligns items along the cross axis.
  • flex-wrap — Defines whether items should wrap onto a new line.

CSS Grid:

  • Grid Layout is a two-dimensional system that allows you to create both rows and columns. It is more powerful than Flexbox for complex layouts because it can handle both vertical and horizontal alignment at the same time.
  • Grid lets you define explicit columns and rows within a container, and then you can place items in these grid areas.

Key Properties of Grid:

  • display: grid; — Defines the grid container.
  • grid-template-columns — Defines the number and size of columns.
  • grid-template-rows — Defines the number and size of rows.
  • grid-gap — Defines the spacing between grid items.

Key Differences:

  • Flexbox is for one-dimensional layouts (either row or column), while Grid is for two-dimensional layouts (both rows and columns).
  • Flexbox is best used when you need alignment in a single direction, and Grid is more suitable for complex layouts with both rows and columns.

2. How do box-sizing: border-box; and box-sizing: content-box; differ?

The box-sizing property controls how the total width and height of an element are calculated.

  • box-sizing: content-box; (default):
    • The width and height you set only apply to the content of the element. The padding and border are added to the width and height, so the element's actual size is larger than what you specified.
    • Formula: total width = width + padding + border

Example:

div {
  width: 200px;
  padding: 20px;
  border: 10px solid black;
}
/* Total width = 200px + 20px (left padding) + 20px (right padding) + 10px (border) = 260px */
  • box-sizing: border-box;:
    • The width and height you set include padding and borders, so the total size of the element stays exactly as you specify, and the padding/border is included within the element's dimensions.
    • Formula: total width = width (padding and border are inside the specified width).

Example:

div {
  width: 200px;
  padding: 20px;
  border: 10px solid black;
  box-sizing: border-box;
}
/* Total width = 200px (including padding and border) */

Key Difference: With content-box, the width and height are calculated excluding padding and border, while with border-box, they are included.

3. What are CSS preprocessors? Can you name a few popular ones?

A CSS preprocessor is a tool that allows you to write CSS in a more dynamic and structured way. They extend CSS by providing features like variables, nested rules, mixins, functions, and more, which are not natively available in CSS.

Popular CSS Preprocessors:

  1. Sass (Syntactically Awesome Stylesheets):
    • Offers features like variables, nested rules, mixins, inheritance, and more.
    • Uses .scss or .sass file extensions.

Example:

$primary-color: blue;
body {
  color: $primary-color;
}
  1. LESS:
    • Similar to Sass, LESS provides variables, mixins, and nested rules.
    • Uses .less file extension.

Example:

@primary-color: blue;
body {
  color: @primary-color;
}
  1. Stylus:
    • A more flexible preprocessor with a syntax that can be more minimalistic than Sass or LESS.
    • Uses .styl file extension.

Benefits of CSS preprocessors:

  • Variables for reusable values.
  • Nested selectors for cleaner code.
  • Mixins and functions for reusable code blocks.
  • Inheritance for code reuse and DRY principles.

4. What is the calc() function in CSS? Provide an example of its use.

The calc() function in CSS allows you to perform calculations to dynamically determine property values. You can combine different units (such as px, %, em, rem) and perform mathematical operations like addition, subtraction, multiplication, and division.

Example:

div {
  width: calc(100% - 20px);
  height: calc(50vh + 10px);
}

In this example, the width of the div will be calculated as 100% of the parent’s width minus 20 pixels. The height will be calculated as half of the viewport height (50vh) plus 10 pixels.

Use case: calc() is useful for responsive layouts, adjusting widths, heights, and other measurements dynamically based on the viewport or parent element's size.

5. How do you create a grid layout using CSS Grid?

To create a grid layout using CSS Grid, you define a grid container with display: grid;, and then you specify the grid columns and rows using properties like grid-template-columns and grid-template-rows. You can also control spacing using grid-gap or gap.

Example

.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* Creates 3 equal-width columns */
  grid-template-rows: 100px 200px; /* Creates 2 rows with fixed heights */
  gap: 10px; /* Spacing between grid items */
}

.item {
  background-color: lightblue;
}

This creates a grid with 3 equal-width columns and 2 rows. The gap property adds space between the grid items.

You can also control how items are placed within the grid using grid-column and grid-row properties.

6. What are media queries, and how do they work in responsive design?

Media queries in CSS allow you to apply styles based on the characteristics of the device or viewport, such as width, height, resolution, or orientation. They are fundamental to creating responsive web design, where the layout adapts to different screen sizes or devices.

Syntax:

@media (max-width: 768px) {
  /* Styles for devices with a max width of 768px (typically tablets and phones) */
  body {
    background-color: lightblue;
  }
}

In this example, the background color will change to lightblue when the viewport width is 768px or less.

Common media query examples:

  • @media (max-width: 600px) — For small mobile devices.
  • @media (min-width: 768px) — For tablets and larger devices.
  • @media (orientation: portrait) — For devices in portrait mode.

Media queries allow you to create flexible and adaptive layouts based on the device’s characteristics, making your website responsive across various screen sizes.

7. How does position: fixed; behave differently than position: absolute;?

Both position: fixed; and position: absolute; are used to position elements, but they behave differently in terms of their reference point and positioning:

  • position: fixed;:
    • The element is positioned relative to the viewport (the visible part of the browser window).
    • It remains fixed in place even when the page is scrolled.
    • Use case: Fixed navigation bars, floating action buttons, etc.

Example:

.fixed-element {
  position: fixed;
  top: 10px;
  left: 10px;
}
  • position: absolute;:
    • The element is positioned relative to its closest positioned ancestor (an element with any position other than static).
    • If no positioned ancestor exists, it will be positioned relative to the initial containing block (usually the <html> element).
    • Use case: Placing elements inside specific sections or containers.

Example:

.absolute-element {
  position: absolute;
  top: 10px;
  left: 10px;
}

Key difference: Fixed positioning is relative to the viewport and stays in place while scrolling, while absolute positioning is relative to a container or the page itself.

8. What is a CSS reset, and why is it used?

A CSS reset is a set of CSS rules that removes or normalizes the default styling provided by browsers (like margins, padding, font sizes, etc.). The purpose of a reset is to create a consistent baseline for styling elements across different browsers, preventing differences in rendering due to default browser styles.

Example of a simple CSS reset:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

Why is it used?

  • Ensures consistent layout behavior across different browsers.
  • Eliminates default margins, paddings, and other styles that may cause layout inconsistencies.
  • Gives you more control over the styling of elements from scratch.

9. How do @import and link tags differ when importing CSS into an HTML document?

Both the @import and link tags are used to include external CSS files in an HTML document, but they work differently:

  • <link>:
    • It is a self-closing HTML tag and is placed inside the <head> section.
    • It is the preferred method for linking to external stylesheets.

Example:

<link rel="stylesheet" href="styles.css">
  • @import:
    • It is a CSS rule that can be placed inside a <style> block or an external CSS file.
    • It is less efficient because the browser must load the imported CSS file after parsing the main CSS file.

Example:

@import url('styles.css');

Key difference: The link tag is more efficient and is preferred for linking external CSS files, while @import can cause performance issues and is typically used for importing within other CSS files.

10. Explain the concept of CSS specificity and how it affects the application of styles.

CSS specificity determines which CSS rule is applied when multiple rules could apply to the same element. It is based on the types of selectors used (e.g., element, class, or ID selectors).

Specificity hierarchy (from lowest to highest):

  1. Universal selector (*) has the lowest specificity.
  2. Type selectors (e.g., div, p) have low specificity.
  3. Class selectors (e.g., .class) have higher specificity.
  4. ID selectors (e.g., #id) have the highest specificity.
  5. Inline styles (e.g., style="...") override all other selectors.

Example:

p {
  color: red;
}

.class {
  color: blue;
}

#id {
  color: green;
}
  • The text inside a <p> element will be green if it has the id="id" because ID selectors have the highest specificity.
  • If the same element has a class .class, it will be blue, since class selectors have higher specificity than type selectors.

Conclusion: CSS specificity ensures that the most specific selector gets applied. If two rules have the same specificity, the latter rule (in the stylesheet) will override the previous one.

11. What is the difference between opacity and rgba in CSS when setting colors?

  • opacity:
    • The opacity property in CSS controls the transparency level of an entire element, including its content (text, images, etc.). The value of opacity ranges from 0 (fully transparent) to 1 (fully opaque). This affects the entire element and everything inside it, making it see-through.

Example:

div {
  opacity: 0.5; /* Makes the element 50% transparent */
}
  • Key difference: opacity affects the entire element, including its background, text, and child elements.
  • rgba():
    • rgba() stands for Red, Green, Blue, Alpha, and it is used for setting a color with transparency on just the color (background, borders, etc.) but not the entire element. The alpha value (ranging from 0 to 1) controls the transparency of the color itself, while the other three values (red, green, blue) define the color.

Example:

div {
  background-color: rgba(255, 0, 0, 0.5); /* Semi-transparent red */
}


  • Key difference: rgba() only affects the color value (like background or text), whereas opacity affects the transparency of the entire element and its content.

12. How do you achieve multi-column layouts in CSS?

To create a multi-column layout, CSS provides the columns property or the column-count and column-gap properties, which allow you to divide an element's content into multiple columns.

Using columns shorthand:

div {
  columns: 3; /* Create 3 columns */
  column-gap: 20px; /* Sets the space between the columns */
}

Using column-count and column-gap separately:

div {
  column-count: 3; /* Creates 3 columns */
  column-gap: 20px; /* Sets the space between columns */
}

Key properties:

  • column-count: Specifies the number of columns.
  • column-gap: Sets the space between the columns.
  • column-rule: Adds a rule (line) between the columns.

Example:

div {
  column-count: 3;
  column-gap: 30px;
  column-rule: 1px solid black;
}

This will create a layout where the content inside the div is divided into 3 columns with a 30px gap between them and a 1px black line separating the columns.

13. What is the difference between visibility and display in CSS?

  • visibility:
    • The visibility property controls whether an element is visible or hidden, but it still takes up space in the document flow.
    • Values:
      • visible (default): The element is visible.
      • hidden: The element is hidden, but it still occupies space in the layout.

Example:

div {
  visibility: hidden; /* Hides the element but still takes up space */
}
div {
  visibility: hidden; /* Hides the element but still takes up space */
}
  • display:
    • The display property controls the element's rendering behavior and can completely remove an element from the layout if set to none. An element with display: none does not occupy space in the layout.
    • Values:
      • block: The element behaves like a block-level element.
      • inline: The element behaves like an inline element.
      • none: The element is removed from the layout entirely.

Example:

div {
  display: none; /* Hides the element and it doesn't take up space */
}

Key Difference:

  • visibility: hidden makes an element invisible but keeps its space in the layout.
  • display: none removes the element from the layout entirely, meaning it doesn’t occupy space or affect other elements.

WeCP Team
Team @WeCP
WeCP is a leading talent assessment platform that helps companies streamline their recruitment and L&D process by evaluating candidates' skills through tailored assessments