Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent flex items from stretching

Tags:

html

css

flexbox

People also ask

How do I make my flex elements not stretch?

By default, the child elements of a flexbox container will stretch vertically to fill the height of the container. This can be prevented by using the align-self property on the child element that you do not want to stretch. This Pen is owned by dev on CodePen.

Why are my flex items overflowing?

The initial value of the flex-wrap property is nowrap . This means that if you have a set of flex items that are too wide for their container, they will overflow it.

How do you control the flex item width?

A flexbox item can be set to a fixed width by setting 3 CSS properties — flex-basis, flex-grow & flex-shrink. flex-basis : This property specifies the initial length of the flex item. flex-grow : This property specifies how much the flex item will grow relative to the rest of the flex items.


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?