Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

center

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.

like image 573
knightrider Avatar asked Sep 06 '25 16:09

knightrider


2 Answers

You could do this

<div style="text-align:center;">
    <div style="border:1px solid #000; display:inline-block;">Div 1</div>
    <div style="border:1px solid red; display:inline-block;">Div 2</div>
</div>  

http://jsfiddle.net/jasongennaro/MZrym/

  1. wrap it in a div with text-align:center;
  2. give the innder divs a display:inline-block; instead of a float

Best also to put that css in a stylesheet.

like image 193
Jason Gennaro Avatar answered Sep 09 '25 05:09

Jason Gennaro


Could this do for you? Check my JSFiddle

And the code:

HTML

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

CSS

div.container {
    background-color: #FF0000;
    margin: auto;   
    width: 304px;
}

div.div1 {
    border: 1px solid #000;
    float: left;
    width: 150px;
}

div.div2 {
    border: 1px solid red;
    float: left;
    width: 150px;
}
like image 20
Jules Avatar answered Sep 09 '25 07:09

Jules