Search code examples
htmlcssflexbox

Prevent flex items from stretching


Sample:

div {
  display: flex;
  height: 200px;
  background: tan;
}
span {
  background: red;
}
<div>
  <span>This is some text.</span>
</div>

I have two questions, please:

  1. Why does it basically happen to the span?
  2. What is the right approach to prevent it from stretching without affecting other flex items in a flex container?

Solution

  • You don't want to stretch the span in height?
    You have the possiblity to affect one or more flex-items to don't stretch the full height of the container.

    To affect all flex-items of the container, choose this:
    You have to set align-items: flex-start; to div and all flex-items of this container get the height of their content.

    div {
      align-items: flex-start;
      background: tan;
      display: flex;
      height: 200px;
    }
    span {
      background: red;
    }
    <div>
      <span>This is some text.</span>
    </div>

    To affect only a single flex-item, choose this:
    If you want to unstretch a single flex-item on the container, you have to set align-self: flex-start; to this flex-item. All other flex-items of the container aren't affected.

    div {
      display: flex;
      height: 200px;
      background: tan;
    }
    span.only {
      background: red;
      align-self:flex-start;
    }
    span {
        background:green;
    }
    <div>
      <span class="only">This is some text.</span>
      <span>This is more text.</span>
    </div>

    Why is this happening to the span?
    The default value of the property align-items is stretch. This is the reason why the span fill the height of the div.

    Difference between baseline and flex-start?
    If you have some text on the flex-items, with different font-sizes, you can use the baseline of the first line to place the flex-item vertically. A flex-item with a smaller font-size have some space between the container and itself at top. With flex-start the flex-item will be set to the top of the container (without space).

    div {
      align-items: baseline;
      background: tan;
      display: flex;
      height: 200px;
    }
    span {
      background: red;
    }
    span.fontsize {
      font-size:2em;
    }
    <div>
      <span class="fontsize">This is some text.</span>
      <span>This is more text.</span>
    </div>

    You can find more information about the difference between baseline and flex-start here:
    What's the difference between flex-start and baseline?