Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make flex items take content width, not width of parent container

Tags:

html

css

flexbox

People also ask

How do you get flex items to take the content width?

Use align-items: flex-start on the container, or align-self: flex-start on the flex items. No need for display: inline-flex . An initial setting of a flex container is align-items: stretch . This means that flex items will expand to cover the full length of the container along the cross axis.

How do I make my Flex container not full width?

Instead of display: flex on the container, use display: inline-flex . This switches the container from block-level (which takes the full width of its parent) to inline-level (which takes the width of its content).

How do you control flex width?

Instead of flex-direction: column , you can try a wrapping flexbox using flex-wrap: wrap ; and you can set: flex-basis: 50% for the half width divs. flex-basis: 100% for the full width divs.

Which of these properties can control the size of Flex items?

The flex-shrink property. The flex-shrink property specifies the flex shrink factor, which determines how much the flex item will shrink relative to the rest of the flex items in the flex container when negative free space is distributed.


Use align-items: flex-start on the container, or align-self: flex-start on the flex items.

No need for display: inline-flex.


An initial setting of a flex container is align-items: stretch. This means that flex items will expand to cover the full length of the container along the cross axis.

The align-self property does the same thing as align-items, except that align-self applies to flex items while align-items applies to the flex container.

By default, align-self inherits the value of align-items.

Since your container is flex-direction: column, the cross axis is horizontal, and align-items: stretch is expanding the child element's width as much as it can.

You can override the default with align-items: flex-start on the container (which is inherited by all flex items) or align-self: flex-start on the item (which is confined to the single item).


Learn more about flex alignment along the cross axis here:

  • How does flex-wrap work with align-self, align-items and align-content?

Learn more about flex alignment along the main axis here:

  • In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

In addtion to align-self you can also consider auto margin which will do almost the same thing

.container {
  background: red;
  height: 200px;
  flex-direction: column;
  padding: 10px;
  display: flex;
}
a {
  margin-right:auto;
  padding: 10px 40px;
  background: pink;
}
<div class="container">
  <a href="#">Test</a>
</div>