Using CSS to detect no search results, and display a placeholder

I was having an issue displaying a No Results placeholder – the code-behind was PHP, and it was using a while statement to display the results, when there were no results the code was adding whitespace so showing a placeholder using :empty was not an option. The obvious thing to do was to change the while to an if/else but I have no real understanding of PHP so that was not really an option.

After a lot of searching for solutions, including PHP, JavaScript and removing unnecessary whitespace in the PHP I ended up going back to basics and using adjacent sibling selectors – which turned out to be a very simple solution. It’s probably not ideal but it worked perfectly for me, and it could do for you as well.

You simply add your No Result placeholder as the last element in the results array and you add a rule to to hide it when your CSS rule matches the . So,

<ul>
<li>value</li>
<li class="noval"><span class="sr-only">No Results Found</li>
</ul>

will trigger hiding the placeholder, but

<ul>
<li class="noval"><span class="sr-only">No Results Found</li>
</ul>

will display it.

The CSS is very simple:

li.noval {
list-style-type:none;
margin-left: -40px;
background-image: url(//aupairireland.ie/svg/bg-norecords.svg);
background-size: 150px;
background-position:left center;
background-repeat: no-repeat;
min-height: 110px;
}
li + li.noval {
display: none;
}

And that’s it. 

I added the .sr-only text for accessibility reasons, because I am using an image for the placeholder, so you can ignore it if you are displaying a text message. The CSS for .sr-only is:

.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
border: 0;
}

The results are below:


The only drawback I can think of, in terms of usability and accessibility is that some screen readers may pick up the .noval content if it’s visually hidden – if that’s a major concern it should be a fairly simple matter to hide or display that using JavaScript to add the HTML5 attribute hidden or the Aria attribute aria-hidden="true" to the <li class="noval">

Here’s the Codepen for it 

See the Pen Using CSS to detect no search results, and display a placeholder by Cormac Maher (@Cormac-Maher) on CodePen.light