简体   繁体   中英

Center align 2 fixed width divs side by side within parent div

I am trying to get 2 divs centered exactly within a parent div. Both child divs take the height of the parent div. I've tried float:left and right with margin: 0 auto. I don't want one div centered while the other is offset a little. I would like div 1 right side to be in the exact center while div 2 left side to be in the exact center too. (I would prefer using CSS but if needed JS would be fine).

Here is the HTML:

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

Here is the CSS:

.green {
    height:50px;
    width:100%;
    background-color:#9fbe3c;
}
.div1 {
    height:100%;
    width:141px;
    margin:0 auto;
}
.div2 {
    width:141px;
    height:100%;
    float:right;
    position:relative;
    top:-50px;
}

Fiddle

For some reason div 2 was being pushed out of the parent block. I've tried display:inline-block and that did not work so I just used position relative.

You can do it like this

HTML

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

CSS

.green {
    height:50px;
    width:100%;
    background-color:#9fbe3c;
  text-align: center;
}
.div1, .div2 {
    height:100%;
    width:141px;
    margin:0 auto;
  display: inline-block
}

Try adding a text-align: center and display: inline-block while removing the margin/float logic.

Here is the modified fiddle: http://jsfiddle.net/Gad4C/9/

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM