HTML 和 CSS --- 边距问题 [英] HTML and CSS --- margin Problems

查看:28
本文介绍了HTML 和 CSS --- 边距问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你在第一个盒子(red_box)上放置一个margin-top,它会拉动或影响包含盒子(容器).为什么?

.red_box {背景颜色:红色;边距顶部:10px;右边距:20px;底边距:20px;`左边距:40px;高度:100px;宽度:300px}.green_box {背景颜色:绿色;边距顶部:40px;右边距:20px;底边距:20px;左边距:40px;高度:100px;宽度:300px}.容器 {宽度:500px;高度:500px;背景颜色:黄色;}

<div class="red_box">红盒子

<div class="green_box">绿盒子

解决方案

这种行为的原因是 边缘崩溃:

<块引用>

在 CSS 中,两个或多个盒子(可能是也可能不是兄弟)的相邻边距可以组合形成一个边距.

您可以使用 .container 上的nofollow noreferrer">overflow 规则:

.red_box {背景颜色:红色;边距顶部:10px;右边距:20px;底边距:20px;`左边距:40px;高度:100px;宽度:300px;}.green_box {背景颜色:绿色;边距顶部:40px;右边距:20px;底边距:20px;左边距:40px;高度:100px;宽度:300px}.容器 {宽度:500px;高度:500px;背景颜色:黄色;溢出:隐藏;/* <-- 这可以防止边距折叠 */}

<div class="red_box">红盒子

<div class="green_box">绿盒子

If you place a margin-top on the first box (red_box) it pulls or affects the containing box (container). Why?

.red_box {
  background-color: red;
  margin-top: 10px;
  margin-right: 20px;
  margin-bottom: 20px;`
  margin-left: 40px;
  height: 100px;
  width: 300px
}

.green_box {
  background-color: green;
  margin-top: 40px;
  margin-right: 20px;
  margin-bottom: 20px;
  margin-left: 40px;
  height: 100px;
  width: 300px
}

.container {
  width: 500px;
  height: 500px;
  background-color: yellow;
}

<div class="container">
  <div class="red_box">
    red box
  </div>
  <div class="green_box">
    green box
  </div>
</div>

解决方案

The reason for this behaviour is margin collapsing:

In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin.

You can prevent it with an overflow rule on the .container:

.red_box {
  background-color: red;
  margin-top: 10px;
  margin-right: 20px;
  margin-bottom: 20px;`
  margin-left: 40px;
  height: 100px;
  width: 300px;
}

.green_box {
  background-color: green;
  margin-top: 40px;
  margin-right: 20px;
  margin-bottom: 20px;
  margin-left: 40px;
  height: 100px;
  width: 300px
}

.container {
  width: 500px;
  height: 500px;
  background-color: yellow;
  overflow: hidden; /* <-- this prevents margin collapsing */
}

<div class="container">
  <div class="red_box">
    red box
  </div>
  <div class="green_box">
    green box
  </div>
</div>

这篇关于HTML 和 CSS --- 边距问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆