开发者

Center two divs in the middle of a wrapper

开发者 https://www.devze.com 2023-03-02 04:16 出处:网络
I have this CSS problem: <div id=\"wrap\"> <div id=\"left\">I am div 1</div> <div id=\"right\">I am div 2</div>

I have this CSS problem:

<div id="wrap">
    <div id="left">I am div 1</div>
    <div id="right">I am div 2</div>
</div>

I am trying to make "I am div 1 I am div 2" center inside the wrap div. Not sure how to explain it. The design is only in percent, l开发者_运维技巧iquid design and I'm stuck.

Any ideas?


If I understand your question correctly, this should work:

#wrap {
    background: #e7e7e7;
    padding: 5%;
    text-align: center;
    width: 80%;  
}

#left, #right {
     background: #ccc;
     display: inline-block;    
     padding: 2%;   
}

View Example

This will center two div blocks within the wrap, side by side.


EDIT: 2015 Flexbox Solution

Flexbox is much more widely supported now and is most likely a better solution for this situation. There are some quirks that come along with the above inline-block method, such as horizontal spacing and vertical alignment issues. Here is the flexbox solution:

#wrap {
    background: #e7e7e7;
    display: flex;
    justify-content: center;
    padding: 5%; 
    width: 80%;  
}

#left, #right {
    background: #ccc;
    padding: 2%;   
}

View Example

Be sure to check Can I Use to confirm that flexbox is supported in the browsers you are supporting.

2019 Edit: Commenter MC9000 brought up that my example is not responsive in percents, as the original question mentioned. I've updated my examples to show that this works with percentage based sizing just like it does with pixel based sizing.


text-align:center; would center this for you:

#wrap{
  width:50%;
  border: 1px solid #000;
}

#left, #right{
  text-align: center;
}

Demo: http://jsfiddle.net/DbNs6/1/

0

精彩评论

暂无评论...
验证码 换一张
取 消