html - 为什么 div 的内容会受到其显示的影响?

标签 html css flexbox

总结:我想并排放置两个文本 block (包含在 div 中),这两个 block 通过 flexbox 进行管理.然而,他们的内容受到 display 的影响。 parent 的div .

(以下代码在JSFiddle)

为什么会出现下面的代码

.flex {
  display: flex;
  flex-direction: row;
}
<div class="flex">
  <div class="flex">
    this is the content of the left box
  </div>
  <div class="flex">
    this is the content of the right box
    <p>
      with some paragraphs
    </p>
    <p>
      more paragraphs
    </p>
  </div>
</div>

显示为

enter image description here

我原以为这两段会在“这是右框的内容”下面。为什么它们遵循 div 的行对齐方式s 类 flex ? 我怎样才能阻止他们这样做? (我的印象是 display: flex 只会覆盖 div 容器,但这些 div 的内容将呈现为默认定位)

最佳答案

因为 flex-container 的子项是 flex-items 并且失去了它们的默认显示属性。

甚至文本节点...

Each in-flow child of a flex container becomes a flex item, and each contiguous run of text that is directly contained inside a flex container is wrapped in an anonymous flex item.

来自Spec

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.

因此,要实现您想要的布局,请确保子 div 不是 display:flex

.flex {
  display: flex;
  flex-direction: row;
}
.flex div {
  border: 1px solid grey;
}
<div class="flex">
  <div class="">
    this is the content of the left box
  </div>
  <div class="">
    this is the content of the right box
    <p>
      with some paragraphs
    </p>
    <p>
      more paragraphs
    </p>
  </div>

</div>

关于html - 为什么 div 的内容会受到其显示的影响?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35070847/

相关文章:

javascript - 滚动 overflow hidden 的 div 以将其中的元素居中

html - Angular flex 盒 : how to set max width to a div

javascript - 从 css、JavaScript 获取样式

javascript - 使用 jQuery 添加类仅适用于第一个元素

javascript - 加载时禁用 div 不起作用,为什么?

jquery - 无限滚动 jQuery 插件 : how to fix loading graphic from "animating" left to center of page?

javascript - Material Design Lite 的复选框不适用于列表

html - Firefox 中的 Flexbox inline-flex 错误

html - 即使使用 flex-shrink : 0,Flex 元素也会收缩

html - 展示图片和轮播标题