CSS Interview Questions

28 Questions
HTML & CSS

HTML & CSS

Web DevelopmentFrontend

Question 5

How do you target an element with multiple classes in CSS?

Answer:

To target an element with multiple classes in CSS, you combine the class names in the selector by placing them together with no spaces between the class names. Each class name in the selector should be prefixed with a dot (.).

Example

Suppose you have the following HTML element with multiple classes:

<div class="box highlight special"></div>

CSS Selector for Multiple Classes

To target this specific element that has all three classes (box, highlight, and special), you would write a CSS rule like this:

.box.highlight.special {
    background-color: yellow;
    border: 2px solid red;
}

Explanation

  • .box.highlight.special: This selector targets elements that have all three classes (box, highlight, and special) applied to them.
  • The styles defined in this rule will only apply to elements that have all these classes.

Key Points

  • The order of the class names in the CSS selector does not matter. For example, .highlight.box.special will have the same effect as .box.highlight.special.
  • The element must have all the specified classes for the styles to be applied. If the element has only some of the classes, or if the classes are applied in a different combination, the styles will not be applied.

Example of Multiple Class Selectors in Action

Here’s a more complete example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        /* Targets elements with all three classes: box, highlight, and special */
        .box.highlight.special {
            background-color: yellow;
            border: 2px solid red;
            padding: 20px;
        }

        /* Targets elements with only the box class */
        .box {
            background-color: lightgray;
            padding: 20px;
        }
    </style>
    <title>Multiple Class Selector Example</title>
</head>
<body>
    <div class="box">This box has only the "box" class.</div>
    <div class="box highlight">This box has "box" and "highlight" classes.</div>
    <div class="box highlight special">This box has "box", "highlight", and "special" classes.</div>
</body>
</html>

Output Explanation

  • The first div only has the box class, so it gets a light gray background.
  • The second div has both box and highlight classes, but it won’t match the .box.highlight.special selector, so it only gets the light gray background from .box.
  • The third div matches the .box.highlight.special selector and will have a yellow background and a red border.

Recent job openings