javauser35
javauser35

Reputation: 1315

Add content if the element is not empty

I want to add content (with :before selector) only if span has value.

If the span is empty I don't want to add content with :before selector.

How can I do it with css?

<!DOCTYPE html>
<html>

<head>
  <style>
    span.b::before {
      content: "\2022"
    }
    
    .span.b:empty {}
  </style>
</head>

<body>

  <div class="a">
    <span class="b">AAA</span>
  </div>

</body>

</html>

Upvotes: 4

Views: 193

Answers (2)

user9077625
user9077625

Reputation:

You can also use a code like this

span.b::before {
    content: "\2022";
}
span.b:empty::before {
    content: inherit;
}

You can use the property inherit to give the default styles. Because it's normally inherit. But if the browser don't know the value inherit for any propery, you can use it likes initial

Upvotes: 0

tao
tao

Reputation: 90188

You were close. You're looking for:

span.b:not(:empty)::before {
  content:"\2022"
}

span.b:not(:empty)::before {
  content:"\2022"
}
<div class="a">
  <span class="b">AAA</span>
</div>
<div class="a">
  <span class="b"></span>
</div>

Upvotes: 4

Related Questions