w3resource

HTML CSS Exercise: Style the element which is not empty

Solution:

HTML Code:

<!doctype html><!-- Declares the document type and version of HTML -->
<html><!-- Opening tag for the HTML document -->
<head><!-- Opening tag for the head section which contains metadata -->
<title>HTML CSS Exercise - Style the element which is not empty</title><!-- Title of the HTML document -->
<style> /* Opening tag for CSS styling */
.container { /* Styles for elements with class 'container' */
background: #5ac4ed; /* Sets the background color to a shade of blue */
height: 150px; /* Sets the height of the container */
width: 200px; /* Sets the width of the container */
margin:10px; /* Sets the margin around the container */
}

.container:empty { /* Styles for empty elements with class 'container' */
background: #ec8007; /* Sets the background color to a shade of orange */
}
</style><!-- Closing tag for CSS styling -->
</head><!-- Closing tag for the head section -->
<body><!-- Opening tag for the body section which contains the content -->
<div class="container"><!-- I am empty --></div><!-- Empty container div with a comment -->
<div class="container">I am not empty</div><!-- Container div with text content -->
</body><!-- Closing tag for the body section -->
</html><!-- Closing tag for the HTML document -->

Explanation:

  • The HTML document consists of two <div> elements with the class 'container'.
  • The first <div> is empty, containing only a comment <!-- I am empty -->.
  • The second <div> contains text content "I am not empty".
  • CSS styling is applied within <style> tags.
  • The .container class sets the background color, height, width, and margin of the container.
  • The :empty pseudo-class selects elements that have no children (including text nodes), and applies a different background color to them.

Live Demo:

See the Pen style-the-element-which-is-not-empty-answer by w3resource (@w3resource) on CodePen.


Supported browser

Firefox logo Chrome logo Opera logo Safari logo Internet Explorer logo
YesYesYesYesYes

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.