您的位置:首页 > 运维架构

重新认识margin-top和margin-bottom

2016-11-18 17:21 225 查看
        margin-top和margin-bottom是HTML网页设计中常用的两个样式属性,提起margin和padding的区别想来无人不知无人不晓,那么让我们实现如下功能:

1、“应付总额”所在div距父div的距离为20px;
2、“寄送至”所在div距离上面兄弟div的距离为10px;
3、“寄送至”所在div距离父div的距离为20px;
有些童鞋会不假思索的这样写代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>重新认识margin-top和margin-bottom</title>
</head>
<body>
<div style="background-color:red;">
<div style="margin-top:20px;">应付总额: ¥45.00</div>
<div style="margin-top:10px;margin-bottom:20px;">寄送至: 中国 河南省郑州市金水区</div>
</div>
</body>
</html>
浏览器渲染后的效果如图所示:


        看到这个图是不是很吃惊:我们只实现了第二个要求,为什么会这样?一句话,我们对margin-top和margin-bottom的真实作用还没有充分的认识:margin-top用于设置其所作用的标签的上外距离,可是该上外边距相对于谁呢?是父div吗?呵呵呵,不是,因为该父div没有边界,对于margin-top来说根就参照不了,其实现在参照的是body;margin-bottom同样如此。可以如何解决这个问题呢?
第一种方法:最简单的方式是为父div添加边框
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>重新认识margin-top和margin-bottom</title>
</head>
<body>
<div style="background-color:red;border:2px solid green;">
<div style="margin-top:20px;">应付总额: ¥45.00</div>
<div style="margin-top:10px;margin-bottom:20px;">寄送至: 中国 河南省郑州市金水区</div>
</div>
</body>
</html> 浏览器渲染后的效果如图所示:



        第二种方法:使用padding-top和padding-bottom实现
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>重新认识margin-top和margin-bottom</title>
</head>
<body>
<div style="padding-top:20px;padding-bottom:20px;background-color:red;">
<div>应付总额: ¥45.00</div>
<div style="margin-top:10px;">寄送至: 中国 河南省郑州市金水区</div>
</div>
</body>
</html> 浏览器渲染后的效果如图所示:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: