使柔性项目的内容宽度,而不是父容器的宽度 [英] Make flex items take content width, not width of parent container

查看:108
本文介绍了使柔性项目的内容宽度,而不是父容器的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个容器< div> ,其中显示:flex 。它有一个小孩< a>

我怎样才能让孩子出现内联?


$ b


$ b $具体来说,我怎样才能让孩子的宽度由其内容决定,而不是扩大到父母的宽度? b

我试过了:

我把孩子设置为 display:inline-flex ,但它仍然占用了整个宽度。我也尝试了所有其他的显示属性,但没有任何效果。



示例:

  .container {background:red; height:200px; flex-direction:column;填充:10px; display:flex;} a {display:inline-flex;填充:10px 40px;背景:粉红色;}  

 < div class =container > < a href =#>测试< / a>< / div>  

http://codepen.io/donpinkus/pen/YGRxRY

解决方案使用 align-items:flex-start align-self:flex-start 在弹性项目上。

不需要显示:inline-flex






一个flex容器的初始设置是 align-items:stretch 。这意味着flex项目将扩展到沿横轴覆盖整个容器。



align-self 属性与 align-items 完全相同,除了 align-self 适用于 flex项目而 align-items 适用于 flex容器 通过默认情况下, align-self 继承 align-items

由于您的容器是 flex-direction:column ,横轴是水平的, align-items:stretch align-items:flex-start 来覆盖默认值。 (限于单个项目)上的容器(由所有弹性项目继承)或 align-self:flex-start






了解更多关于 cross axis 横轴的信息。

b
$ b

详细了解沿着主轴 p>


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>

http://codepen.io/donpinkus/pen/YGRxRY

解决方案

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:

这篇关于使柔性项目的内容宽度,而不是父容器的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆