top of page arrow
How-to:
CSS :empty Pseudo-Class

There are almost limitless options for formatting a page in html using css. Using pseudo-class selectors can allow a developer to create one base style and apply additional styles to others of its type without having to create another set of elements for every case. For a deeper dive into pseudo-class selectors, visit the MDN Docs.


Let's start with a basic shape...

This shape has some content. It serves as the basic template for a shape...in this case, our box.

This is how our basic box shape is styled in the stylesheet:




	.box {
		position: relative;
		width: 60%;
		height: 240px;
		background: linear-gradient(135deg, var(--colorPrimary), var(--colorTertiary));
		border: 5px solid var(--colorText);
		border-radius: 40px;
		background-color: transparent;
		margin: 50px auto;
		display:flex;
		justify-content: center;
		align-items: center;
		color:var(--colorAccent);
		font-size: var(--lengthlg1);
		font-weight: 900;
		text-align: center;
		padding: 15px;
		text-shadow: 1px 1px var(--colorShadow);
		box-shadow: 5px 5px 10px var(--colorSecondary);
	}

This box is empty, so the :empty pseudo class is active:


.box:empty {
	background: linear-gradient(135deg, var(--colorQuad), var(--colorToneOrange));
}

Since we already set the main style for the box, we only have to include the elements we want to change in our stylesheet.


The next box has a comment in the html, but is still considered empty. Comments, processing instructions and css content do not constitute content.

html:

<div class="box">
<!-- comments don't count as content -->
</div>

This empty shape is specifically targeted as the 7th of its type using the :nth-of-type() selector along with the :empty pseudo type to change the styles:


.box:nth-of-type(7):empty {
	background: linear-gradient(135deg, var(--colorButton), var(--colorToneGreen));
}

Note: Though this is respectively the 4th and 5th empty div of class "box", they are the 7th and 9th divs within the parent (main) container on this page. Something to remember when you are targeting the empty divs.


Using the :nth-of-type() selector combination, and a complete lack of taste, we can position, shape, add background images, and color empty spaces and use them to format specific areas.


.box:nth-of-type(9):empty {
	background: url(https://www.duemler.com>/code/images/blur.png);
	background-size: cover;
	width: 20vw;
	height: 249px;
	border-radius: 0 50% 0 50%;
	border: 15px dashed var(--colorToneYellow);
	transform: rotate(-35deg);
	margin-right: 5%;
}

Using a little imagination, styling empty spaces and using them in page design is just one more tool on the workbench for crafting the best user experience possible.