Shrink flex item to fit content

Here’s a sample:

body {
  display: flex;
  flex-direction: column;
}

a {
  background: lightGreen;
}
<a href="#">This is some text.</a>

DEMO

The <a> element stretches as long as the page width. How can we shrink it so it fits the content?

Use the align-items property.
The default is stretch which will fill the width (height in case of row direction).
Other values will fit the content.

2 Likes

I want the anchor to be at the beginning of the line and start , flex-start , and baseline values seem to do the trick. Is there any preference/difference?

flex-start I think would be the natural choice.
I’m not really sure is baseline “works” in a column direction, I can’t imagine how it would, since a baseline is horizontal. So maybe that’s just for flex rows, though that’s only my guess.

1 Like

As @SamA74 said above flex-start will do what you want.

body {
  display: flex;
  flex-direction: column;
  align-items:flex-start;
}

However I’m a big fan of auto margins if you are only interested in the one element then this would work instead.

a {
  background: lightGreen;
  margin-right:auto;
}

It all depends on what comes next :slight_smile:

Note that as you are in the flex-direction:column the elements won’t stack sideways if that’s what you were thinking. All direct child elements will stack down the left side and be shrink to fit.

4 Likes

To target a single flex-item, we can also use align-self: flex-start.

1 Like