使flex项目获取内容宽度,而不是父节点的全宽度 [英] Make flex item take content width, not full width of parent

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

问题描述

我有一个容器< div> display:flex 。它有一个孩子< a> 。如何让孩子看起来内联?

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?

我尝试的:

我将子项设置为 display:inline-flex ,但它仍然占用了全宽。我也尝试了所有其他显示属性,但没有什么效果。

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.

示例:

.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

推荐答案

解决方案



而不是 inline-flex ,给出锚元素 align-self:flex-start

flex容器的初始设置是 align-items:stretch 。这意味着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.

align-self property与 align-items 的功能相同,但前者适用于flex项目,后者适用于容器。

The align-self property does the same thing as align-items, but the former applies to flex items while the latter applies to the container.

默认情况下, align-self 继承 align-items 的值。

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

由于您的容器 flex-direction:column ,横轴为水平, align-items:

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

您可以使用 align-items覆盖默认值:在容器(将被所有flex项目继承)或 align-self:flex-start

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

详细信息:

  • 8.3. Cross-axis Alignment: the align-items and align-self properties
  • In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

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

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