How to not display css padding when span element is empty
If you don't require support for IE8, you can use pseudo-state :empty
(here for more examples ) to reset padding for all instances of .myClassDie
without content, using the following code.
.myClassDie:empty
{
padding:0;
}
Updating your working example, it becomes:
.myClassDer
{
font-size: 34px;
color:white;
background: blue;
color: white;
border-radius: 25px;
padding: 7px;
width: auto;
height: auto;
}
.myClassDie
{
font-size: 34px;
color:black;
background: red;
color: white;
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>
In which I inserted two <span class="myClassDie">
to show you the behaviour with and without content.
Due to effective invisibility of "empty" case, if you want a more compact solution, you can collapse the two separate rules into only one, simply setting:
.myClassDie:not(:empty)
{
font-size: 34px;
color:black;
background: red;
color: white;
border-radius: 25px;
padding: 7px;
width: auto;
height: auto;
}
In this case, only if .myClassDie
is not empty, you'll apply all properties.
This is equivalent for this specific case, but if you want to see this DIV also if empty, limiting only to reset padding (for example because it has fixed size or borders), you must use first solution, not the more compact one.
Little precisation about :empty pseudo-class
Previous examples run correctly only if empty elements are effectively empty, this means that this code <span class="myClassDie"></span>
is correctly targeted, but this one (that contains a whitespace) <span class="myClassDie"> </span>
isn't.
In general, this could be an issue because often code is dynamically generated or otherwise contains white spaces due to code indentation.
In the past, Mozilla introduced its proprietary pseudo-class :-moz-only-whitespace
, but no other browser currently supports this yet.
W3 also tried to solve this kind of problems, initially with analogue :blank
pseudo-class (again with no browser support) in "Selectors Level 3", but this did not have expected success.
So, since beginning of 2018, W3 modified its definition to represent empty user input, rather than empty elements and contemporarily modified :empty definition to consider also white-spaces, but currently this last feature is not implemented too in different browsers.
Empty pseudo class only checks for empty text
.myClassDie:empty{
padding:0;
}
But for whitespaces use blank pseudo class
.myClassDie:blank{
padding:0;
}