Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

align 2 divs horizontally inside a third container div [duplicate]

Tags:

html

css

I have the following code:

<div id="container">
    <div id="div1">Div 1</div>
    <div id="div2">Div 2</div>
</div>

I want to be able to have #box1 and #box2 one next to the other inside the container. Container is centered

like image 824
cppit Avatar asked Aug 01 '12 17:08

cppit


1 Answers

This will center the container, and have the two divs within it centered, while separating the styles from the actual content:

HTML:

<div id="container">
    <div>Div 1</div>
    <div>Div 2</div>
</div>

CSS:

#container > div
{
    display: inline-block;
    border: solid 1px #000;
}
#container
{
    border: solid 1px #ff0000;
    text-align: center;
    margin: 0px auto;
    width: 40%;
}   

Working example:

http://jsfiddle.net/JLjjK/

2017 Update:

Flexbox is becoming much more commonplace. Here's a way to achieve similar results with Flexbox:

HTML:

<div class="outer">
  <div>1</div>
  <div>2</div>
</div>

CSS:

.outer {
  border: 1px solid #000;
  display:flex;
  justify-content: center;
  padding: 3px;
}
.outer > div {
  border: 1px solid #000;
  margin:2px;
}

Example: https://jsfiddle.net/pb61a1cj/1/

like image 185
Alex W Avatar answered Oct 26 '22 05:10

Alex W