Center parent div with float children

前端 未结 4 1903
逝去的感伤
逝去的感伤 2021-01-24 12:09

Parent hasnt got a defined width because there are unknown number of children inside.

Why do children fall into new line and how to prevent that? Children need to be on

4条回答
  •  梦谈多话
    2021-01-24 12:12

    What happens here is that when you use translate the element is visually re-positioned, though from a document flow perspective it is still positioned at 50% left.

    So as you can see in this sample, they wrap at the same time though one think that the first shouldn't as there is space left, but there isn't, as technically the first has the same position as the second, hence it wrap at the same time.

    .wrap {
      position: absolute;
      left: 50%;
      top: 150px;
      height:40px;
    }
    .wrap.translate {
      top: 50px;
      transform: translateX(-50%);
    }
    .box {
     width:40px;
     height:40px;
     float:left;
     background:red;
     margin-right:1px;
    }
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10


    The simplest and best way to solve this is to make the wrap an inline-block and set text-align: center on its parent, in this case the body

    body {
      text-align: center;
    }
    .wrap {
      display: inline-block;
      height:40px;
    }
    .box {
     width:40px;
     height:40px;
     float:left;
     background:red;
     margin-right:1px;
    }
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10


    Yet another is to make the box's inline-block and set text-align: center on the wrap

    Note, to defeat the white space between inline block elements, I also change the markup so each box's end and start tag are on the same line. Here is a few more ways to solve that: how-to-remove-the-space-between-inline-block-elements

    .wrap {
      height:40px;
      text-align: center;
    }
    .box {
     display: inline-block;
     width:40px;
     height:40px;
     background:red;
     margin-right:1px;
    }
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10


    If you don't need to support older browsers you can also use Flexbox

    .wrap {
      display: flex;
      justify-content: center;
      height:40px;
    }
    .box {
     width:40px;
     height:40px;
     background:red;
     margin-right:1px;
    }
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

提交回复
热议问题