inside container with display flex become corrupted

后端 未结 3 1507
离开以前
离开以前 2021-02-02 08:06

This behavior is a little odd and weird. If there is a container with its display property set to flex and flex-direction to column<

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-02 08:19

    According to HTML5 Rendering - The hr element, it is expected to be rendered with this style:

    hr { color: gray; border-style: inset; border-width: 1px; margin: 0.5em auto; }
    

    Specifically, note margin-left: auto, margin-right: auto.

    Those styles are used to center a block element horizontally. According to Calculating widths and margins - Block

    If both margin-left and margin-right are auto, their used values are equal. This horizontally centers the element with respect to the edges of the containing block.

    In a block layout this effect is only noticeable if the block has an explicit width, otherwise the block will grow to cover all its containing block.

    In Flexbox it's similar: the default align-self: auto and align-items: stretch make flex items grow to cover the flex line in the cross axis (horizontal one in column layout), and auto margins can also be used to center.

    However, there is a big difference: according to Cross Size Determination, align-self: stretch does not affect flex items with auto margins:

    If a flex item has align-self: stretch, its computed cross size property is auto, and neither of its cross-axis margins are auto, the used outer cross size is the used cross size of its flex line, clamped according to the item’s min and max cross size properties. Otherwise, the used cross size is the item’s hypothetical cross size.

    Then, you can fix this problem by removing the auto margins:

    hr {
      margin-left: 0;
      margin-right: 0;
    }
    

    .container {
      padding: 20px;
      display: flex;
      flex-direction: column;
    }
    hr {
      margin-left: 0;
      margin-right: 0;
    }

    Title


    This is some content

    Alternatively, forcing a certain width through width or min-width would counteract the shrinking (more technically, the lack of stretch) caused by the auto margins.

提交回复
热议问题