stack
stack

Reputation: 10228

How to remove top margin when element is empty?

Here is my HTML structure:

p {
  margin: 0;
  border: 1px solid;
}
small {
  display: block;
  margin-top: 40px;
  border: 1px solid #999;
}
small + span {
  display: block;
  border: 1px solid #ccc;
}
<p>content</p>
<small>tags</small>
<span>edit</span>

All fine. Sometimes <small> element is empty. Something like this:

<p>content</p>
<small></small>
<span></span>

In this case, I want to remove the margin-top of <small>.

Is that possible using pure CSS? It should be noted I don't want to use JS.

Upvotes: 2

Views: 135

Answers (1)

Stickers
Stickers

Reputation: 78696

You could try using a combination of :not and :empty pseudo-classes.

small:not(:empty) {
  margin-top: 40px;
}

The negation CSS pseudo-class, :not(X), is a functional notation taking a simple selector X as an argument. It matches an element that is not represented by the argument. X must not contain another negation selector. -MDN


The :empty pseudo-class represents any element that has no children at all. Only element nodes and text (including whitespace) are considered. Comments or processing instructions do not affect whether an element is considered empty or not. -MDN

Upvotes: 4

Related Questions