Center two divs in the middle of a wrapper

前端 未结 2 2095
忘掉有多难
忘掉有多难 2021-02-05 14:57

I have this CSS problem:

I am div 1
I am div 2
相关标签:
2条回答
  • 2021-02-05 15:19

    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 讨论(0)
  • 2021-02-05 15:43

    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.

    0 讨论(0)
提交回复
热议问题