【问题标题】:Make flex container take width of content, not width 100%使 flex 容器采用内容的宽度,而不是宽度 100%
【发布时间】:2017-07-29 22:14:41
【问题描述】:

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

.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>

【问题讨论】:

    标签: html css flexbox


    【解决方案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>

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

    【讨论】:

      【解决方案2】:

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

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

      这种大小调整行为类似于display: blockdisplay: inline-block

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

      【讨论】:

      • 哦,是的,那更好。没有单独的包装器。
      猜你喜欢
      • 2017-03-01
      • 2017-08-08
      • 1970-01-01
      • 2017-12-03
      • 2015-09-11
      • 1970-01-01
      相关资源
      最近更新 更多