IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原]重新认识margin-top和margin-bottom

    wangshuxuncom发表于 2016-11-18 17:21:08
    love 0

            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>
    浏览器渲染后的效果如图所示:




沪ICP备19023445号-2号
友情链接