Two Divs on the same row and center align both of them

Viewed 136970

I have two divs like this

<div style="border:1px solid #000; float:left">Div 1</div>
<div style="border:1px solid red; float:left">Div 2</div>

I want them to display on the same row, so I used float:left.

I want both of them to be at center of the page as well, so I tried to wrap them with another div like this

<div style="width:100%; margin:0px auto;">
  <div style="border:1px solid #000; float:left">Div 1</div>
  <div style="border:1px solid red; float:left">Div 2</div>
</div>

But it doesn't work. If I change the code to this

<div style="width:100%; margin-left:50%; margin-right:50%">
  <div style="border:1px solid #000; float:left">Div 1</div>
  <div style="border:1px solid red; float:left">Div 2</div>
</div>

then it's going to the center, but the horizontal scrollbar is there and it seems like it's not really centered as well.

Can you please kindly suggest to me how can I achieve this? Thanks.

Edit: I want the inner div (Div 1 and Div 2) to be center align as well.

7 Answers

Align to the center, using display: inline-block and text-align: center.

.outerdiv
{
    height:100px;
    width:500px;
    background: red;
    margin: 0 auto;
    text-align: center;
}

.innerdiv
{
    height:40px;
    width: 100px;
    margin: 2px;
    box-sizing: border-box;
    background: green;
    display: inline-block;
}
<div class="outerdiv">
    <div class="innerdiv"></div>
    <div class="innerdiv"></div>
</div>

Align to the center using display: flex and justify-content: center

.outerdiv
{
    height:100px;
    width:500px;
    background: red;
    display: flex;
    flex-direction: row;
    justify-content: center;
}

.innerdiv
{
    height:40px;
    width: 100px;
    margin: 2px;
    box-sizing: border-box;
    background: green;
}
<div class="outerdiv">
    <div class="innerdiv"></div>
    <div class="innerdiv"></div>
</div>

Align to the center vertically and horizontally using display: flex, justify-content: center and align-items:center.

.outerdiv
{
    height:100px;
    width:500px;
    background: red;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items:center;
}

.innerdiv
{
    height:40px;
    width: 100px;
    margin: 2px;
    box-sizing: border-box;
    background: green;
}
<div class="outerdiv">
    <div class="innerdiv"></div>
    <div class="innerdiv"></div>
</div>

Please take a look on flex it will help you make things right,

on the main div set css display :flex

the div's that inside set css: flex:1 1 auto;

attached jsfiddle link as example enjoy :)

https://jsfiddle.net/hodca/v1uLsxbg/

Related