What do we need display:inline-block; for?
If you want that a <div> with the id="element" oder or another block-element adapts to the size of its content one has to add the following line of CSS code:
.element{display:inline-block}
we wrap #element in <div id="wrapper"> and we add
#wrapper{text-align:center}
We achieved our goal, see picture:
For reference our code is:
#index.html
#wrapper
.element and some more content, and more, and more...
.element .after
.element .after
#styles.css
#wrapper-a{
text-align:center;
background:pink;
}
.element{
display:inline-block;
background:#396;
padding:10px;
}
.after{
background:#369;
}
#wrapper-a *{
margin:0;
}
The problem
In the following example, we get a problem using the presented method: the white gaps between the nav elements were not intended.
index.html – (source)
styles.css – (source)
nav a {
display: inline-block;
padding: 5px;
background: #933;
color:#fff;
}
Alternatives display:table and display:table-cell
We can circumvent our problem as follows…
… in example 1:
#wrapper-a{display:table}
.element{display:table-cell}
… in example 2:
nav a{display:table-cell}
Solve the Problem
The following methods originate from CSS-Tricks. Each item is a unique method.
- Remove the whitespaces between inline-block elements, because those cause for the white gaps
- Insert HTML-comments (<!– –>) with to comment out all whitespace.
- Use negative margins, like
margin-right:-4px; - Omit the closing tag (e.g. </li>)
- Use CSS3 Flex-box (browser support).
- Set font-size of whitespace to zero:
nav{font-size:0}, nav a{font-size:16px}