Up until this point, we have relied upon an element’s default value of being inline or block-level to define whether it would be presented next to other elements horizontally or placed beneath previous elements in a new “block”.
display:
The CSS display:
property allows developers to explicitly specify and/or change these properties for any element. In addition, this property also allows developers to “hide” an element.
This greatly increases the developers ability to create layouts that support the presentation of content in a web browser.
The display:
property is called on the actual element it is being applied to (as opposed to a parent element holding child elements).
display:
SetTo illustrate, we’re going to look at styled navigation lists. Below is the control, with no additional display:
property applied:
display: inline;
The display: inline;
rule forces elements to act like inline elements, similar to how the <span>
elements acted above. Inline elements, unlike block-level elements:
width
properties).NOTE: Since inline elements “flow” it is also important to recognize that their content can “flow” onto the next line…
display: inline-block;
The display: inline-block;
rule, like display: inline;
, removes ‘new line’s inherent in block elements. Unlink display: inline;
, display: inline-block;
also forces elements to respect margin, and vertical spacing properties/rules.
However, this also means these elements will expand, horizontally to fill the parent-container. Therefore, you must explicitly set the width of these elements.
In the following example, notice that the same basic HTML code is used three times in a row. However, the second and third examples have display: inline;
& display: inline-block;
, respectively.
Notice the differences of these display techniques. Particularly with regard to horizontal and vertical spacing.
A menu without a set display:
A menu with items displayed inline:
A menu with items displayed inline as blocks:
As you can see, we have used display: inline;
& display: inline-block;
to create our first header menus! And in fact, it is often used for that purpose. (More on that later…)
display: block;
Just like the display property can be used to turn ‘block’ elements into inline
or inline-block
elements, it can also be used to turn ‘inline’ elements into block
elements.
This technique is often used to create vertical menus out of lists, as in the example below. Notice how the use of display: block;
on the second set changes the behavior of the elements.