# margin
# 尺寸的概念
<div class="div">width:100px</div>
<style>
body {
background-color: pink;
}
.div {
width: 100px;
height: 100px;
background-color: white;
border: 10px solid red;
margin: 10px;
}
</style>
# 针对上面的例子:
# 元素尺寸:offsetWidth,包含 border。(100+10+10=120px)
# 元素内部尺寸:clientWidth,不包含 border。(100px)
# 元素外部尺寸:包含 margin。(100+10+10+10+10=140px)
# margin 初始值为 0
# margin:auto
# 规则:
# 1. 如果一侧定值,一侧 auto,则 auto 为剩余空间大小
子 div 距离右边距 20px,距离左边距为剩余的 80px;
<div class="p">
width:200px;height:200px;
<div class="c">width: 100px; height:100px</div>
</div>
<style>
body {
background: pink;
}
.p {
width: 200px;
height: 200px;
background: white;
}
.c {
width: 100px;
height: 100px;
background: red;
margin-right: 20px;
margin-left: auto;
}
</style>
# 2. 如果两侧均是 auto,则平分剩余空间
左右边距为 50px
<div class="p">
width:200px;height:200px;
<div class="c">width: 100px; height:100px</div>
</div>
<style>
body {
background: pink;
}
.p {
width: 200px;
height: 200px;
background: white;
}
.c {
width: 100px;
height: 100px;
background: red;
margin-left: auto;
margin-right: auto;
}
</style>
# 3.margin:auto 只针对对应方向的自动填充,默认文档流为从左到右,如果希望垂直居中,需要改变父元素文档流 writing-mode
<div class="p">
width:200px;height:200px;
<div class="c">width: 100px; height:100px</div>
</div>
<style>
body {
background: pink;
}
.p {
width: 200px;
height: 200px;
background: white;
writing-mode: vertical-lr;
}
.c {
width: 100px;
height: 100px;
background: red;
margin-top: auto;
margin-bottom: auto;
}
</style>
但是会影响到水平方向,更好的方法是使用绝对定位。
<div class="p">
width:200px;height:200px;
<div class="c">width: 100px; height:100px</div>
</div>
<style>
body {
background: pink;
}
.p {
position: relative;
width: 200px;
height: 200px;
background: white;
}
.c {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
width: 100px;
height: 100px;
background: red;
margin: auto;
}
</style>
1.margin-right 为负数,可以增加原容器的宽度,实现子元素两边对齐。
2.底部留白用margin,padding会有兼容问题
3.margin-bottom:-9999px;padding-bottom:9999px可以实现多列等高布局,IE8以上可以用table-cell。
4.定高容器的子元素的 margin-bottom 或者宽度定死的子元素的 margin-right 的 定位“失效”。
# margin 合并
margin 合并并非 bug
1.非浮动和绝对定位的块级元素 2.不考虑 writing-mode,只发生在垂直方向
# 合并规则
1.正正取大 2.正负取计算值 3.负负取绝对值大的值