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

时间:2017-03-09 04:22:54

标签: html css css3 flexbox frontend

在下面的示例中,我有一个按钮,其中包含以下样式...

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

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

但它会自动缩放到100%而不是内容的宽度。您可以设置显式宽度,但这样就不允许文本自然换行。

如何创建一个内部文本以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 个答案:

答案 0 :(得分:10)

而不是容器上的display: flex,请使用display: inline-flex

这会将容器从块级别(取其父级的全宽)切换到内联级别(取其内容的宽度)。

此调整行为类似于display: blockdisplay: inline-block

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

答案 1 :(得分:1)

编辑: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>

然后,您可以在容器上设置最大宽度,文本将换行到多行,但保留正确的垂直居中。

我在最近的博文中详细说明了这一点:https://lukeboyle.com/css-buttons-solved-flexbox/