Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center multiple inline-block elements with CSS?

Tags:

css

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.

like image 628
JoJo Avatar asked Jan 05 '12 19:01

JoJo


People also ask

How do I center multiple elements in CSS?

Just add margin: auto and a fixed width to the element you want to center, and the margins will force the element to center.

How do I center an inline block in HTML?

Try using this: margin: 0 auto; Or text-align: center; on the parent <div> ...

How do you align inline block elements?

To align things in the inline direction, use the properties which begin with justify- . Use justify-content to distribute space between grid tracks, and justify-items or justify-self to align items inside their grid area in the inline direction.

How do you center an inline block button?

You can center inline-block (and inline) elements by setting text-align: center on a parent element.


2 Answers

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

like image 86
Jakub Avatar answered Oct 06 '22 00:10

Jakub


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

like image 21
Nate B Avatar answered Oct 05 '22 23:10

Nate B