How to Make Flex Items Take the Content Width

You can make flex items take the content width instead of the width of the parent container with CSS properties. The problem is that a flex container’s initial setting is align-items: stretch; meaning that items expand to cover the container’s full length along the cross axis.

We suggest one of the following methods to overcome this problem: you can use either the CSS align-items or align-self property.

Solution with the CSS align-items property

In the example below, we have an <a> element within a <div> container. We set the align-items to the "flex-start" value on the container. Besides, we set the display to "flex", the flex-direction to "column" and add padding, height, and background. For the <a> element, we specify padding and background.

Example of making a flex item take the content width by using the align-items property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      .container {
        background: #b5bab6;
        height: 150px;
        flex-direction: column;
        padding: 10px;
        display: flex;
        align-items: flex-start;
      }
      a {
        padding: 10px 40px;
        background: #55e6e0;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <a href="#">Some text</a>
    </div>
  </body>
</html>

Result

Both the align-items and align-self properties do the same. The difference is that align-items applies to the flex container, while align-self applies to flex items.

Solution with the CSS align-self property

Instead of the align-items property, in our next example, we use the align-self property set to "flex-start" on the flex item.

Example of making a flex item take a content width by using the align-self property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      .container {
        background: #d1d1d1;
        height: 150px;
        flex-direction: column;
        padding: 10px;
        display: flex;
      }
      a {
        padding: 10px 40px;
        background: #ed8aeb;
        align-self: flex-start;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <a href="#">Some text</a>
    </div>
  </body>
</html>

Do you find this helpful?

Related articles