Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

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

I have a container <div> with display: flex. It has a child <a>.

How can I make the child appear "inline"?

Specifically, how can I make the child's width determined by its content, and not expand to the width of the parent?

What I tried:

I set the child to display: inline-flex, but it still took up the full width. I also tried all other display properties, but nothing had an effect.

Example:

.container {
  background: red;
  height: 200px;
  flex-direction: column;
  padding: 10px;
  display: flex;
}
a {
  display: inline-flex;
  padding: 10px 40px;
  background: pink;
}
<div class="container">
  <a href="#">Test</a>
</div>
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

Learn more about flex alignment along the main axis here:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...