Hiding Elements using CSS
We have plenty of options at our disposal at hiding elements with CSS. In this post we will explore the options we have and more importantly the pros and cons of each choice. The ability to hide elements is essential in modern websites and web applications, it is quite commonly used alongside Javascript as well.
Display
Using the display: none;
is probably the most common one that is used to hide elements. The benefit of using the display property is that it does not render the box and therefore does not take up any space on load. However the HTML is in the document and can later be manipulated using Javascript
CSS
.block2{
display: none;
}
Demo
[codepen_embed height=”600″ theme_id=”0″ slug_hash=”wGGYRr” default_tab=”result” user=”michaelgearon”]See the Pen wGGYRr by Michael Gearon (@michaelgearon) on CodePen.[/codepen_embed]
Visibility
The visibility: hidden
property and value is different to the display property because the tag is still not visible however you will notice that space is allocated for it on the page. What this means is that it is rendered but it is just invisible.
One of the interesting facts with the hidden property is that the property does not inherit by default. For example if you had a container element for your box and then more tags inside this, and then you added the visibility: hidden
to the container it would only affect the container and not the tags inside it.
CSS
.block2{
visibility: hidden;
}
Demo
[codepen_embed height=”600″ theme_id=”0″ slug_hash=”qZZJzd” default_tab=”result” user=”michaelgearon”]See the Pen Hiding Elements using CSS – Visibility by Michael Gearon (@michaelgearon) on CodePen.[/codepen_embed]
Opacity
The opacity property controls how transparent an item is, so it is rendered but again invisible. We set the opacity value to 0 to visually hide the property, although it can still be interacted with. For more information about the opacity property I did a blog post about it.
CSS
.block2{
opacity: 0;
}
Demo
[codepen_embed height=”600″ theme_id=”0″ slug_hash=”XddyWL” default_tab=”result” user=”michaelgearon”]See the Pen Hiding Elements using CSS – Opacity by Michael Gearon (@michaelgearon) on CodePen.[/codepen_embed]
Position
This is not commonly used anymore, but the position property can make tags seem invisible. So we use three properties, position, top and left. We set the tag is to be absolute which takes it out of it’s natural flow, and then say to position is -9999px top and left, which by theory makes it hidden to the browser window.
CSS
.block2{
position:absolute;
top: -9999px;
left: -9999px;
}
Demo
[codepen_embed height=”600″ theme_id=”0″ slug_hash=”vGGQEg” default_tab=”result” user=”michaelgearon”]See the Pen Hiding Elements using CSS – Position by Michael Gearon (@michaelgearon) on CodePen.[/codepen_embed]
Written by
Senior Interaction Designer and Co-Author to Tiny CSS Projects