Hide an Element – display:none or visibility:hidden?
Hiding an element can be done by setting the
display property to
none. The element will be hidden, and the page will be displayed as if the element is not there:
visibility:hidden; also hides an element.
However, the element will still take up the same space as before. The element will be hidden, but still affect the layout:
Override The Default Display Value:
As mentioned, every element has a default display value. However, you can override this.
Changing an inline element to a block element, or vice versa, can be useful for making the page look a specific way, and still follow the web standards.
A common example is making inline
<li> elements for horizontal menus:
Note: Setting the display property of an element only changes how the element is displayed, NOT what kind of element it is. So, an inline element with
display: block; is not allowed to have other block elements inside it.
The following example displays <span> elements as block elements:
The following example displays <a> elements as block elements:
<script> element uses
display: none; as default.
A block-level element always starts on a new line and takes up the full width available (stretches out to the left and right as far as it can).
Examples of block-level elements:
- <h1> – <h6>
An inline element does not start on a new line and only takes up as much width as necessary.
This is an inline <span> element inside a paragraph.
Examples of inline elements:
The display Property
display property specifies if/how an element is displayed.
Every HTML element has a default display value depending on what type of element it is. The default display value for most elements is
Using width, max-width and margin: auto;
As mentioned in the previous chapter; a block-level element always takes up the full width available (stretches out to the left and right as far as it can).
width of a block-level element will prevent it from stretching out to the edges of its container. Then, you can set the margins to auto, to horizontally center the element within its container. The element will take up the specified width, and the remaining space will be split equally between the two margins:
Note: The problem with the
<div> above occurs when the browser window is smaller than the width of the element. The browser then adds a horizontal scrollbar to the page.
max-width instead, in this situation, will improve the browser’s handling of small windows. This is important when making a site usable on small devices:
Tip: Resize the browser window to less than 500px wide, to see the difference between the two divs!
Here is an example of the two divs above:
border: 3px solid #73AD21;
border: 3px solid #73AD21;