theProCoder
theProCoder

Reputation: 435

How to style divs which do not have any elements in it?

I would like to know if I can select a div which does not have any elements in it in CSS.

For example:

HTML:

<body>
    <!-- div with some elements inside of it -->
    <div>
        ...
    </div>

    <!-- divs with nothing inside of them -->
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</body>

If this was the body of my HTML code, I would like to select the last four empty divs.

Upvotes: 0

Views: 126

Answers (1)

law_81
law_81

Reputation: 2430

You can use :empty pseudo-class. It represents any element that has no children. MDN

section{
  display:flex;
}
div {
  width: 50px;
  height: 50px;
  background: red;
  margin: 10px;
}

div:empty {
  background: black;
}
<section>
  <!-- div with some elements inside of it -->
  <div>
    Text Text Text
  </div>

  <!-- divs with nothing inside of them -->
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</section>

Upvotes: 1

Related Questions