Inline-Block

In addition to using floats, another way we can position content is by using the display property in conjunction with the inline-block value. The inline-block method, as we’ll discuss, is primarily helpful for laying out pages or for placing elements next to one another within a line.

Recall that the inline-block value for the display property will display elements within a line while allowing them to accept all box model properties, including height, width, padding, border, and margin. Using inline-block elements allows us to take full advantage of the box model without having to worry about clearing any floats.

Inline-Block in Practice

Let’s take a look at our three-column example from before. We’ll start by keeping our HTML just as it is:

<header>...</header>
<section>...</section>
<section>...</section>
<section>...</section>
<footer>...</footer>

Now instead of floating our three <section> elements, we’ll change their display values to inline-block, leaving the margin and width properties from before alone. Our resulting CSS will look like this:

section {  display: inline-block;  margin: 0 1.5%;  width: 30%;}

Unfortunately, this code alone doesn’t quite do the trick, and the last <section> element is pushed to a new row. Remember, because inline-block elements are displayed on the same line as one another, they include a single space between them. When the size of each single space is added to the width and horizontal margin values of all the elements in the row, the total width becomes too great, pushing the last <section> element to a new row. In order to display all of the <section> elements on the same row, the white space between each <section> element must be removed.

Removing Spaces Between Inline-Block Elements

There are a number of ways to remove the space between inline-block elements, and some are more complex than others. We are going to focus on two of the easiest ways, both of which happen inside HTML.

The first solution is to put each new <section> element’s opening tag on the same line as the previous <section> element’s closing tag. Rather than using a new line for each element, we’ll end and begin elements on the same line.

Last updated