css - Flex 元素宽度与子项相同

标签 css flexbox

我正在尝试制作一个容器元素,一个 flex 元素,其宽度与其跨度文本子项的宽度相同。通过检查代码片段的结果可以看出,尽管容器 .calc-text-container 占用的空间比子元素多,即使 flex-grow-property 设置为 0 .

有没有办法达到预期的效果?

.calc {
  width: 230px;
  background: green;
  height: 100px;
  display: flex;
  justify-content: center;
  flex-direction: column;
}
.calc a {
  display: flex;
  justify-content: center;
}
.calc-icon-container {
  margin-right: 1em;
}
.calc-text-container {
  flex: 0 0 0;
  background: rgba(20,200,0,0.8);
}
<div class="calc">
  <a href="#">
    <div class="calc-icon-container"><span class="calc-icon">🔫</span></div>
	<div class="calc-text-container"><span class="calc-text">To do something megagiga</span></div>
  </a>
</div>

最佳答案

只是 flex :0 0 0;将完成这项工作。

.calc {
  width: 230px;
  background: green;
  height: 100px;
  display: flex;
  justify-content: center;
  flex-direction: column;
}
.calc a {
  display: flex;
  justify-content: center;
}
.calc-icon-container {
  margin-right: 1em;
}
.calc-text-container {
  flex: 0 0 0; // or just flex: 0;
  background: rgba(20,200,0,0.8);
}
<div class="calc">
  <a href="#">
    <div class="calc-icon-container"><span class="calc-icon">🔫</span></div>
	<div class="calc-text-container"><span class="calc-text">Reallylongword Short shortandlong</span></div>
  </a>
</div>

关于css - Flex 元素宽度与子项相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42528088/

相关文章:

css - 表格单元格内的垂直间距

html - 让 flex child 根据 sibling 的高度成长

javascript - Bootstrap 容器之外的箭头

angular - SVG&CSS : label of marker path does not display in IE

html - Flexbox 高度百分比

html - 如何在 flexbox 中垂直对齐文本?

html - 如何确保img最大宽度永远不会使flex sibling 溢出父级

jquery - 如何仅设置 WordPress 帖子标题的单个单词的样式

html - 溢出: hidden doesn't work on :after and :before pseudo elements

javascript - 如何在 css 选择器 :before 上应用 jQuery