【发布时间】:2013-09-28 14:17:35
【问题描述】:
我认为这是一个艰难的过程。
我使用使用float:left 的网格系统。我可以用display:inline-block 重写它,但这不会改变任何事情。
假设我们有两列:
<div class="row">
<div class="column">
<!-- some content here -->
</div>
<div class="column">
<!-- some content here -->
</div>
</div>
如果我在其中放置一个带有 margin-top 的块元素(如 <h1>),我之前会得到内容的非折叠边距。这是正常的,因为浮动元素(或显示:内联块)总是如此。
但我想要有折叠边距。我尝试了很多让它工作,但似乎每个将两个元素相邻放置的 CSS 都会破坏上面内容的折叠边距。
我知道,我可以使用 CSS 来获取元素的第一个子元素以摆脱顶部边缘。但在这种情况下,它将不适用,因为内容是使用 CMS 构建的,并且在我到达元素之前可能存在任意级别的元素深度。
没有 JavaScript 有没有办法做到这一点?
小提琴:http://jsfiddle.net/HerrSerker/ZSV3D/
您可以看到,h1 的 margin-top 和 .header 的 margin-bottom 不会折叠。这是通过float:left 或.column 实现的。
.header {
font-size: 24px;
background: rgba(0,255,0,0.1);
}
h1 {
background: silver;
margin-bottom: 50px;
font-size: 28px;
}
.column {
float: left;
width: 50%;
background: rgba(255,0,0,0.1);
}
h2 {
background: gold;
margin-top: 50px;
font-size: 24px;
}
<div class="header"><h1><h1>Headerh1</h1></h1></div>
<div class="row">
<div class="column"><h2><h2>Col 1, float: left</h2></h2></div>
<div class="column"><h2><h2>Col 2, float: left</h2></h2></div>
</div>
<p>I want a 50 pixel margin between Header and the Cols, but the two margins don't collapse and I end up with 50 + = 100 pixel gap. If it would work, you wouldn't see the light red above col1 and col2</p>
编辑
我当然可以在 CSS 中使用一些后继运算符,例如 header + .row .column h1 { margin-top: 0;}。但这不是我想要的。我想要的是一种设置元素彼此相邻的方法,它可以处理包含元素的边距折叠。
编辑2
简而言之,情况和问题再次出现。
问题比较简单。我有一些 CSS 代码,它允许我设置两个或多个相邻的 div,例如 float:left;宽度:50%。在这些 div 内部是像 h2 这样具有上边距的元素。如果在 div 之前有一个带底边距的 h1。这种情况不允许 h1 和 h2 的边距崩溃。是否有机会通过margin-collapse 将元素彼此相邻放置,而无需手动将margin 设置为零?
否则。是否有机会在不创建新的块格式化上下文的情况下将设置元素彼此相邻?
编辑3:
-------------------------------------------------------------
What it is:
┌─ .header ─────────────────┐
│ ┌─ h1 ──────────────────┐ │
│ │ │ │
│ └───────────────────────┘ │ ┄┄┄┬┄┄┄
└───────────────────────────┘ ┆
┆ margin-bottom of h1
┆
┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┼┄┄┄
┆
┆ margin-top of h2
┌─ .row ────────────────────┐ ┆ not collapsing
│ ┌─ .col ───┐ ┌─ .col ───┐ │ ┄┄┄┴┄┄┄
│ │ ┌─ h2 ─┐ │ │ ┌─ h2 ─┐ │ │
│ │ └──────┘ │ │ └──────┘ │ │
│ └──────────┘ └──────────┘ │
└───────────────────────────┘
-------------------------------------------------------------
What I want:
┌─ .header ─────────────────┐
│ ┌─ h1 ──────────────────┐ │
│ │ │ │
│ └───────────────────────┘ │ ┄┄┄┬┄┄┄
└───────────────────────────┘ ┆ margin-bottom of h1
┆ and margin-top of h2
┌─ .row ────────────────────┐ ┆ collapsing
│ ┌─ .col ───┐ ┌─ .col ───┐ │ ┆
│ │ ┌─ h2 ─┐ │ │ ┌─ h2 ─┐ │ │ ┄┄┄┴┄┄┄
│ │ └──────┘ │ │ └──────┘ │ │
│ └──────────┘ └──────────┘ │
└───────────────────────────┘
-------------------------------------------------------------
【问题讨论】:
-
没有 CSS 也没有小提琴? ://
-
呃,我明白了……我不这么认为:| +1,这是一个艰难的
-
如果我明白你想要什么(我不确定我是否明白),容器也只需要有一个浮动。
-
刚刚意识到这个问题是从 2013 年开始的 - :(
-
3年解决这个问题? :)))
标签: css margin grid-layout