使flex容器采用内容宽度,而不是100%宽度

35

在下面的例子中,我有一个带有以下样式的按钮...

.button-flexbox-approach {
    /* other button styles */
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 1.5rem 2rem;
}

http://codepen.io/3stacks/pen/JWErZJ

使用flexbox将按钮的文本居中,但不自动缩放到内容宽度以外。可以设置显式宽度,但这样会防止文本自然换行。

如何制作一个按钮,使其内部文本使用flexbox居中,但不随容器大小而扩展?

.container {
  width: 100%;
  height: 100%;
}

.button {
/*   Simply flexing the button makes it grow to the size of the container... How do we make it only the size of the content inside it? */
  display: flex;
  justify-content: center;
  align-items: center;
  -webkit-appearance: none;
  border-radius: 0;
  border-style: solid;
  border-width: 0;
  cursor: pointer;
  font-weight: normal;
  line-height: normal;
  margin: 0;
  position: relative;
  text-align: center;
  text-decoration: none;
  padding: 1rem 2rem 1.0625rem 2rem;
  font-size: 1rem;
  background-color: #D60C8B;
  border-color: #ab0a6f;
  color: #fff;
}

.one {
  margin-bottom: 1rem;
}

.two {
/* You can put an explicit width on that, but then you lose the flexibility with the content inside */
  width: 250px;
}
<div class="container">
  <p>
    Button one is flexed with no width and it grows to the size of its container
  </p>
  <p>
    <a class="button one" href="#">Button</a>
  </p>
  <p>
    Button two is flexed with an explicit width which makes it smaller, but we have no flexibility for changing the content
  </p>
  <p>
    <a class="button two" href="#">Button 2</a>
  </p>
</div>

2个回答

51

不要在容器上使用 display: flex,而要使用 display: inline-flex

这将把容器从块级元素(占据父元素的宽度)切换为行内元素(仅占据其内容的宽度)。

这种尺寸行为类似于 display: blockdisplay: inline-block 之间的差异。

有关相关问题和解决方案,请参见:


1
哦,太好了,这样更好。没有单独的包装。 - 3stacks
正是我所需要的。inline-flex。必须让它深入人心并开始使用它。 - Gilad Barner

4

编辑:Michael_B在他的答案中指出,父元素上的inline-flex是这种用例的正确属性。 我已经相应地更新了我的博客文章。

虽然不是理想的解决方法,但如果您将按钮包装在一个内联块级容器中,则按钮将自然地随内容缩放,如下所示:

.button {
  /* other button styles */
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 1.5rem 2rem;
}
<div style="display: inline-block;">
  <a class="button">Button</a>
</div>

您可以在容器上设置max-width,文本将换行为多行,但仍保持正确的垂直居中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接