How can I horizontally align my divs?

前端 未结 9 863
野的像风
野的像风 2020-11-28 03:47

For some reason my divs won\'t center horizontally in a containing div:

相关标签:
9条回答
  • 2020-11-28 04:33

    To achieve what you are trying to do:

    Consider using display: inline-block instead of float.

    0 讨论(0)
  • 2020-11-28 04:33

    Try this:

    .row {
      width: 100%;
      text-align: center; // center the content of the container
    }
    
    .block {
      width: 100px;
      display: inline-block; // display inline with ability to provide width/height
    }​
    

    DEMO

    • having margin: 0 auto; along with width: 100% is useless because you element will take the full space.

    • float: left will float the elements to the left, until there is no space left, thus they will go on a new line. Use display: inline-block to be able to display elements inline, but with the ability to provide size (as opposed to display: inline where width/height are ignored)

    0 讨论(0)
  • 2020-11-28 04:35

    Although not covering this question (because you want to align the <div>s inside the container) but directly related: if you wanted to align just one div horizontally you could do this:

    #MyDIV
    {
        display: table;
        margin: 0 auto;
    }
    
    0 讨论(0)
提交回复
热议问题