CSS CSS Selectors Going Further with Attribute Selectors and Pseudo-Classes :only-child and :empty

Eddie Harmon
seal-mask
.a{fill-rule:evenodd;}techdegree
Eddie Harmon
Front End Web Development Techdegree Student 4,452 Points

Unexpected result when using :empty

While coding along with the video during the :empty explanation, I simply added an <h1></h1> with nothing inside of it. Yet, it did not turn the <h1> tomato as expected. Why is this? My code is below:

<!DOCTYPE html> <html> <head> <title>Selectors</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href='http://fonts.googleapis.com/css?family=Nunito:400,300' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="css/style.css"> <style> body { font-family: 'Nunito', sans-serif; color: #616161; padding: 40px 0; } h1 { text-align: center; } ul { list-style: none; width: 50%; margin: auto; } li { border-bottom: 1px dotted #40918c; padding: 15px 10px; } </style> </head> <body> <h1></h1> <ul> <li>Item 1</li> <li>Item 2 <span>&check;</span></li> <li>Item 3</li> <li>Item 4</li> <li>Item 5</li> <li>Item 6 <span>&check;</span></li> <li></li> <li>Item 8</li> <li>Item 9</li> <li>Item 10</li>
</ul> </body> </html>

BELOW IS THE CSS

li:first-child { background: #52bab3; color: white; }

li:last-child { border: none; }

span:only-child { color: #52bab3; font-size: 1.5em; }

:empty { background-color: tomato; }

1 Answer

Steven Parker
Steven Parker
201,976 Points

When the element is empty, the height collapses so there isn't any background showing. But you could force a minimum height to make it visible:

:empty {
  background-color: tomato;
  height: 1em;
}
Eddie Harmon
seal-mask
.a{fill-rule:evenodd;}techdegree
Eddie Harmon
Front End Web Development Techdegree Student 4,452 Points

Thanks so much, Steven! That is the tricky thing about code: you can be using a concept completely right, but if you don't know all of the "side-effects" of an action, it can rob a ton of your time and energy and trick you into believing you are doing something wrong. Thanks for clarifying this for me!