Search code examples
cssflexboxclearfix

Can I use flexbox to give an element layout, and therefore deprecate clearfix?


Similar, but not the same as Is clearfix deprecated?.

I have a web app targeted at modern browsers. Flexbox is used everywhere for vertical centering. The only real CSS/SASS hack is clearfix:

@mixin clearfix {
    content: "";
    display: table;
    clear: both;
}

Is there any aspect of flexbox I can use to ensure an element contains its children, so I can stop using clearfix hacks?

I understand this is called 'hasLayout' by browser rendering engines.


Solution

  • A flexed item will scale with the size of its children assuming you don't set a specific height, so you won't need to rely on float, or by extension clearfix. I've got a pen where I'm playing with flex at the moment.

    The rules I'm using are:

    .parent {
      display: flex;
      flex-flow: row wrap;
      justify-content: space-between;
      align-content: space-between;
    }
    .child {
      margin-bottom: 1.5%;
    }
    

    And then for each child, I'm specifying a width that I want it to fill.

    For these rules, display:flex tells the parent to display as a flexbox. flex-flow is a short-hand for flex-direction and flex-wrap - in this case I'm telling the parent to have its children sit in a row, and when they reach the end of the available width, wrap down to the next line. justify-content: space-between helps with horizontal spacing between the children, removing the need to cancel a margin at the end of the row. align-content: space-between helps add some vertical spacing. I've found that I do have to add margin-bottom onto the children just to create a little white space.

    A quick caveat, though, is that if you do still need to use floats for whatever reason, it would be good to clear them still.