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

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

问题描述

我有一个带有 display: flex 的容器

.它有一个子.

我怎样才能让孩子看起来内联"?

具体来说,如何让子的宽度由其内容决定,而不是扩展到父的宽度?

我的尝试:

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

示例:

.container {背景:红色;高度:200px;弹性方向:列;填充:10px;显示:弹性;}一个 {显示:inline-flex;填充:10px 40px;背景:粉红色;}

<a href="#">测试</a>

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

解决方案

在容器上使用 align-items: flex-startalign-self: flex-start> 在弹性项目上.

不需要display: inline-flex.

<小时>

弹性容器的初始设置是align-items:stretch.这意味着 flex 项目将沿着交叉轴扩展以覆盖容器的整个长度.

align-self 属性与 align-items 的作用相同,除了 align-self 适用于 flex itemsalign-items 适用于 flex 容器.

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

由于您的容器是 flex-direction: column,所以横轴是水平的,并且 align-items:stretch 正在尽可能地扩展子元素的宽度.

您可以使用容器上的 align-items: flex-start 覆盖默认值(由所有弹性项目继承)或 align-self: flex-start在项目上(仅限于单个项目).

<小时>

在此处了解有关沿横轴的 flex 对齐的更多信息:

在此处了解有关沿主轴的 flex 对齐的更多信息:

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天全站免登陆