How to center multiple inline-block elements with CSS?

Css

Css Problem Overview


I want to horizontally center two (or possibly more) inline-block elements inside a container block element. It should look like this:

--------------------------
|      _____   _____      |
|     |     | |     |     |
|     | foo | | bar |     |
|     |_____| |_____|     |
|_________________________|

However, with my broken code, it is currently looking like this:

--------------------------
| _____   ____            |
||     | |     |          |
|| foo | | bar |          |
||_____| |_____|          |
|_________________________|

HTML

<div>
 <a>foo</a>
 <a>bar</a>
</div>

CSS

div a {
 display: inline-block;
 padding: 1em;
 margin: 1em;
 border: 1px solid black;
}

The reason why the two anchors have to be inline-block and not just plain inline is because I don't want the anchor's padding and margin to overlap.

Css Solutions


Solution 1 - Css

Simply set text-align: center; on the div container.

Solution 2 - Css

Set text-align: center; on the parent element.

Solution 3 - Css

have you tried the following?

div{
   text-align:center;
}

Solution 4 - Css

Either you can try these one

div{
   text-align:center;
}

or set margin auto as shown below

div a{
  margin:auto;
  margin-left:1em;
  margin-right:1em;
  margin-top:1em;
  margin-bottom:1em;
 display:inline-block;
}

A good example is shown here

Solution 5 - Css

Just to be clear ...

<div style="display: inline-block; text-align: center"> 
  ....
</div>

doesn't work with elements of different widths, but

<div style="text-align: center;">
<div style="display: inline-block;">
 ....
</div>
</div>

does

Solution 6 - Css

I used text-align: "center" in the parent container, and that centered the ULs on the page, but it also centered the text in the ULs (not desired). So I added a text-align: "left" to the <ul> so that the text was next to the list-style.

Solution 7 - Css

You can also do

.div {
    display: inline-block center;
    text-align: center;
}

to make the inline block center horizontally!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoJoView Question on Stackoverflow
Solution 1 - CssJakubView Answer on Stackoverflow
Solution 2 - CssNate BView Answer on Stackoverflow
Solution 3 - CssMaksim Vi.View Answer on Stackoverflow
Solution 4 - CssDaniel NyamasyoView Answer on Stackoverflow
Solution 5 - CssVincent QuigleyView Answer on Stackoverflow
Solution 6 - CssJack MasonView Answer on Stackoverflow
Solution 7 - CssMauve17View Answer on Stackoverflow