html - 为什么宽度在 flexbox 中处理不同?

标签 html css flexbox

我最近一直在研究 display:flex,因为我发现它越来越流行。在快速测试中,使用 flex 和非 flex CSS 方法,我意识到,在使用 flex 时,我的宽度和边距总是受到尊重。考虑到我很可能无论如何都需要在元素之间留出间距,这是一种好方法吗?此外,跨度之间的边距从何而来?这就是我的意思:

HTML

<div class="container">
  <div class="box">
    <span class="inner-box">This gives me a 30px X 60px</span>
    <span class="inner-box">This gives me a 30px X 60px</span>
    <span class="inner-box">This gives me a 30px X 60px</span>
  </div>  
  <div class="box2">
    <span class="inner-box">This gives me a width larger than the specified 30px</span>
    <span class="inner-box">This gives me a width larger than the specified 30px</span>
    <span class="inner-box">This gives me a width larger than the specified 30px</span>
  </div>  
</div>

CSS

.box{
  background: orange;
  display:flex;
  flex-direction:row-reverse;
  padding:0 10px;
}

.box2{
  background: green;
  text-align:right;
  padding:0 10px;
}

.inner-box{
  width:30px;
  background:#fff;
  margin:0 0px;
}

注意运行时的宽度 Flexbox

Non-flexbox

DEMO

最佳答案

您正在使用 <span>元素。默认情况下它们是内联的。 width对于内联元素会自动忽略。

在第一个div节 ( .box ),然而, span的内联 display值被父级的 display: flex 覆盖, 它建立了一个 flex formatting context .因此,所有 child 都成为 flex 元素,尊重widthheight .

Flex Items

A flex item establishes a new formatting context for its contents. The type of this formatting context is determined by its display value, as usual. However, flex items themselves are flex-level boxes, not block-level boxes: they participate in their container’s flex formatting context, not in a block formatting context.

source: https://drafts.csswg.org/css-flexbox-1/#flex-items


在第二个div节 ( .box2 ), span元素保留 display: inline , 因为它们没有从 block-formatting context 中删除, 和任何 widthheight分配被忽略。

尝试 display: inline-block : http://codepen.io/anon/pen/yeggOy

引用资料:

关于html - 为什么宽度在 flexbox 中处理不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34567500/

相关文章:

javascript - 根据 HTML 表单值更改动态更新 highcharts 数据

php - 具有多个提交的 PHP 页面上的表单更改页面的 CSS

jquery - html页面加载动画

html - 使用 CSS flexbox 制作一个四方形的照片库

angularjs - 重新加载 Angular 应用程序后没有 index.html

html - php 输出中的内联 css

javascript - 为 W3School 幻灯片编辑 JavaScript 代码

css - 垂直分离 Angular Material 卡片

html - Flexbox - 两个元素的不同对齐方式

javascript - 我如何使用 flexbox 和 Vue.js 将我在右侧发送的蓝色消息和我在左侧接收的黄色消息组合在一起?