To avoid needing support for IE8, you can utilize the pseudo-state :empty
(check here for more examples) to reset padding for all occurrences of .myClassDie
without any content by using this code snippet:
.myClassDie:empty {
padding: 0;
}
If we update your existing example, it will look like this:
.myClassDer {
font-size: 34px;
color: white;
background: blue;
border-radius: 25px;
padding: 7px;
width: auto;
height: auto;
}
.myClassDie {
font-size: 34px;
color: black;
background: red;
border-radius: 25px;
padding: 7px;
width: auto;
height: auto;
}
.myClassDie:empty {
padding: 0;
}
<span class="myClassDer">here</span>
<span class="myClassDie"></span>
<span class="myClassDie">ClassDie but with content</span>
I have added two instances of <span class="myClassDie">
to demonstrate the behavior with and without content.
In cases where the "empty" state is effectively invisible, if you prefer a more concise solution, you can combine the two separate rules into one by simply setting:
.myClassDie:not(:empty) {
font-size: 34px;
color: black;
background: red;
border-radius: 25px;
padding: 7px;
width: auto;
height: auto;
}
This means that only when .myClassDie
is not empty, all properties will be applied.
While this approach works well for this specific scenario, if you want to display the DIV even when empty while only resetting padding (e.g., because of fixed size or borders), then you should stick to the initial solution rather than the more compact one.
A Note on the :empty Pseudo-Class
The previous examples function correctly only when empty elements are truly empty. This implies that the following code
<span class="myClassDie"></span>
is targeted accurately, whereas this one (which includes a whitespace)
<span class="myClassDie"> </span>
isn't.
This can be problematic since code is often dynamically generated or contains white spaces due to indentation.
In the past, Mozilla introduced its proprietary pseudo-class :-moz-only-whitespace
; however, no other browsers currently support it.
W3C initially attempted to address these issues with the analogous :blank
pseudo-class in "Selectors Level 3," which lacked browser support and did not achieve the expected success.
Since the beginning of 2018, W3C altered its definition to represent empty user input instead of empty elements and concurrently revised the :empty definition to encompass white spaces as well. However, this feature has yet to be implemented across various browsers.