CSS Layout - display: inline-block
The display: inline-block Value
Compared to display: inline
, the major
difference is that display: inline-block
allows
to set a width and height on the element.
Also, with
display: inline-block
, the top and bottom margins/paddings are respected,
but with display: inline
they are not.
Compared to display: block
, the major
difference is that display: inline-block
does
not add a line-break after the element, so the element can sit next to other
elements.
The following example shows the different behavior of display: inline
, display: inline-block
and display: block
:
Example
span.a {
display: inline; /* the default for span */
width: 70px;
height: 70px;
padding: 15px;
border: 1px solid blue;
background-color: yellow;
}
span.b {
display:
inline-block;
width: 70px;
height:
70px;
padding: 15px;
border: 1px
solid blue;
background-color: yellow;
}
span.c {
display: block;
width:
70px;
height: 70px;
padding: 15px;
border: 1px solid blue;
background-color: yellow;
}
Try it Yourself »
Use inline-block to Create Navigation Links
One common use for display: inline-block
is to create horizontal navigation links:
Example
.nav {
background-color: yellow;
padding: 15px;
list-style-type: none;
text-align: center;
}
.nav li {
display: inline-block;
font-size: 20px;
padding-left: 20px;
padding-right: 20px;
}
Try it Yourself »
Grid of Boxes
It has been possible for a long time to create a grid of boxes that fills the
browser width and wraps nicely (when the browser is resized), by using the
float
property.
However, the inline-block
value of the display
property makes this easier!
Examples
The old way - using float
(notice that we also need to specify a
clear
property for the element after the floating boxes):
Example
.floating-box {
float: left;
width: 150px;
height: 75px;
margin: 10px;
border: 3px solid #73AD21;
}
.after-box {
clear: left;
}
Try it Yourself »
The same effect can be achieved by using the inline-block
value
of the display
property (notice that no clear
is needed):
Example
.floating-box {
display: inline-block;
width: 150px;
height: 75px;
margin: 10px;
border: 3px solid #73AD21;
}
Try it Yourself »