原创作品,未经许可不得转载
假设页面上有三个相邻的<div>
:
<body>
<div style="background-color:blue">上方的div</div>
<div style="background-color:red">我不希望与别人靠得太近</div>
<div style="background-color:green">下方的div</div>
</body>
运行上方的代码。这三个div
是不是靠得比较近?
如果不希望中间的那个<div>
与其它元素离得太近,可以通过给它设置“外边距”来达到此目的。
“外边距”由margin
样式来设定:
<body>
<div style="background-color:blue">上方的div</div>
<div style="margin:30px; background-color:red">我不希望与别人靠得太近</div>
<div style="background-color:green">下方的div</div>
</body>
运行上方的代码,你会发现中间的那个<div>
与它上、下的<div>
分隔了一定的距离,这就是margin:30px
样式起作用了。
并且,它不仅与上、下保持了一定的距离,而且也与左、右保持了一定的距离。
与padding
一样,margin:30px
是将上、下、左、右四个边的外边距都设为了30px
。
margin
的值同样可以是由四个值组成的组成,这四个值分别对应上、右、下、左四个边的外边距:
<body>
<div style="background-color:blue">上方的div</div>
<div style="margin:10px 20px 30px 40px; background-color:red">
我不希望与别人靠得太近
</div>
<div style="background-color:green">下方的div</div>
</body>
margin:30px
是margin:30px 30px 30px 30px
的简写。
与padding
一样,也有一些简写方式:
margin:10px 20px 10px 20px
可简写成margin:10px 20px
。
margin:10px 20px 30px 20px
可简写成margin:10px 20px 30px
。
同样有专门用来设置某一个边的外边距的样式:
margin-left
样式是设置左外边距。
margin-right
样式是设置右外边距。
margin-top
样式是设置上外边距。
margin-bottom
样式是设置下边外距。
<body>
<div style="background-color:blue">上方的div</div>
<div style="margin-top:10px;
margin-right:20px;
margin-bottom:30px;
margin-left:40px;
background-color:red">
我不希望与别人靠得太近
</div>
<div style="background-color:green">下方的div</div>
</body>
给元素设置margin-left:10px; margin-right:20px; margin-bottom:30px; margin-left:40px
样式,与给它设置padding:10px 20px 30px 40px
样式是等效的。