html - 如何避免 block 元素之间的垂直边距?

标签 html css margin

<分区>

给定一个包含三个 block 元素的页面(此处为:headermainfooter),我想确保三个元素之间没有垂直边距。问题是 main 元素的内容是生成的(使用模板语言),我不能对包含的标记做出太多假设。

考虑这个例子:注意我已经明确地省略了标题的下边距和第一段的上边距。唉,使用 main > *:last-child 对嵌套在 li 元素中的 p 不起作用。有没有一种方法可以概括这一点,例如 margin of e.g.嵌套在 li 中的 p 也被省略了吗?

header {
  background-color: red;
}

main {
  background-color: green;
}

footer {
  background-color: blue;
}

h1 {
  margin-bottom: 0
}

main > *:first-child {
  margin-top: 0
}
<header>
  <h1>
    Hello
  </h1>
</header>
<main>
  <p>
    Some content
  </p>
  <ul>
    <li>
      <p>
        Some list item
      </p>
    </li>
  </ul>
</main>
<footer>
  There should be no white gap above!
</footer>

我希望 main 元素在底部没有任何边距(即使是嵌套元素,例如此处的 p 元素),这样footer 元素位于它的正下方。

最佳答案

我认为您可以针对您的具体情况执行此操作。可能与 main 中的其他内容一起出现其他问题。

header {
  background-color: red;
}

main {
  background-color: green;
}

footer {
  background-color: blue;
}

h1 {
  margin-bottom: 0
}

main > *:first-child {
  margin-top: 0
}
main *:last-child {
   margin-bottom: 0;
}
<header>
  <h1>
    Hello
  </h1>
</header>
<main>
  <p>
    Some content
  </p>
  <ul>
    <li>
      <p>
        Some list item
      </p>
    </li>
  </ul>
</main>
<footer>
  There should be no white gap above!
</footer>

关于html - 如何避免 block 元素之间的垂直边距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58802643/

上一篇:javascript - 为幻灯片制作适当的淡入和淡出

下一篇:html - 尝试将带有网格的 html 容器重写为 flexbox

相关文章:

jquery - H1下方莫名其妙的空间(边距?)

html - 100% 高度/宽度网页上神秘的右边距

javascript - angularjs:指令和 ng-repeat

html - ul li 形状和文字

php - 使用寻路器在 modx revolution 中创建子菜单

css - 是否有一种 CSS 方法可以使 div 在顶部和底部的 2 个固定边距之间垂直居中?

javascript - PHP (CakePHP) - 识别由 JavaScript 创建的表单元素

javascript - 为段落动态分配类

jquery - 模态对话框 Jquery 不适用于 Chrome 和 Internet Explorer

html - block 元素之间垂直的神秘间隙