CSS Display
The display property is one of the most important and fundamental properties in CSS. It defines how an element is displayed and how it behaves within the layout. Every HTML element has a default display value.
display: block; (Block-level)
Block-level elements take up the full available width of their parent element and always start on a new line.
- Characteristics: Occupies a single line, like a rectangular block.
- Dimensions:
width,height,margin, andpaddingcan be set. - Default block-level elements:
<div>,<h1>-<h6>,<p>,<form>,<ul>,<li>, etc.
div {
display: block;
width: 100%;
height: 100px;
background-color: lightblue;
}display: inline; (Inline)
Inline elements do not start on a new line; they flow along with other inline elements on the same line until the end of the line.
- Characteristics: Arranged one after another, like text.
- Dimensions: The width and height of the element are determined by its content. Setting
widthandheightdirectly has no effect. Verticalmarginandpaddingdo not affect surrounding elements. - Default inline elements:
<span>,<a>,<img>,<strong>,<em>,<b>,<i>, etc.
span {
display: inline;
padding: 5px;
background-color: yellow;
}display: inline-block; (Inline-block)
inline-block is a hybrid of block and inline, combining the advantages of both.
- Characteristics: The element sits inline with other elements (like an inline element), but behaves like a block-level element itself.
- Dimensions:
width,height,margin, andpaddingcan be set. - Application: Perfect for creating side-by-side elements with fixed dimensions, such as navigation bar buttons, tag clouds, etc.
a.button {
display: inline-block;
width: 120px;
height: 40px;
background-color: lightgreen;
text-align: center;
line-height: 40px; /* Vertically center text */
}display: none;
display: none; completely removes the element from the page. It is not only invisible but also takes up no space in the layout, as if it never existed.
This is different from visibility: hidden;. visibility: hidden; hides the element, but it still occupies its original space in the layout.
.hidden-element {
display: none;
}display: none; is often used by JavaScript to control the showing and hiding of elements.
display: flex; and display: grid;
These are modern layout modes introduced in CSS3 that greatly simplify the creation of complex layouts.
display: flex;: Turns the element into a "flex container", and its direct children become "flex items". It is excellent for aligning and distributing items in one dimension (row or column).display: grid;: Turns the element into a "grid container". It allows you to create complex layouts in two dimensions (rows and columns).
We will learn Flexbox and Grid in detail in subsequent dedicated chapters.
Summary
display Value | New Line | Width/Height Settable | Vertical Margin/Padding Settable |
|---|---|---|---|
block | Yes | Yes | Yes |
inline | No | No | No |
inline-block | No | Yes | Yes |
none | - | - | - |