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

标签 html css flexbox

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

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

最佳答案

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

这会将容器从 block 级(占用其父级的整个宽度)切换到行内级(占用其内容的宽度)。

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

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

关于html - 使 flex 容器采用内容的宽度,而不是宽度 100%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47984926/

相关文章:

javascript - Angular .js : taking a picture from a subpage - ng-view issue

javascript - 具有多个参数的 jQuery data()?

html - 使用 Flexbox 对齐图像

html - 仅使用 Flex 功能创建特殊网格

html - 如何在重叠容器时使用 "clear" flexbox

jQuery Offset - 在滚动到 Div 时添加类

javascript - 触发器 i :active when keydown on HTML page

css - 如何修复垂直部分?

html - 嗨,我有 2 个关于 css 的问题

javascript - 从另一个子窗口获得焦点子窗口