HTML中行内元素的竖直方向的padding和margin是否真的无效
参考资料:Inline elements and padding
今天写一个导航栏时遇到了一个问题:行内元素的padding-top,padding-bottom和margin-top,margin-bottom是不是真的是无效的? 接下来就这个问题将具体分析: 1.行内元素拥有盒子模型么答案是是的。没错,行内元素跟块级元素一样,同样拥有盒子模型。 2.行内元素的padding-top,padding-bottom和margin-top,margin-bottom是否无效答案同样是是的。盒子模型的width,height和padding-top,padding-bottom和margin-top,margin-bottom设置都是无效的。但是... 3.实战探讨行内元素的padding-top,padding-bottom和margin-top,margin-bottom先来看两个实例: example1:源码: DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>example1title><style type="text/css">*{ margin:0px; padding:0px; text-decoration:none; list-style:none;}#main{ min-width:1280px; background-color:pink; margin:auto; height:800px;}nav{ height:50px; background-color: #ffffff;}nav ul li{ height:50px; float:left; background-color: #ffffff;}a{ line-height:50px; padding:30px; margin:30px; background-color:green; font-size:14px; color:rgb(231,79,77);}style>head><body><div id="main"><header> <nav> <ul> <li><a class="hnav" href="#">首页a>li> <li><a class="hnav" href="#">最新活动a>li> <li><a class="hnav" href="#">项目介绍a>li> <li><a class="hnav" href="#">爱心社区a>li> <li><a class="hnav" href="#">关于我们a>li> ul> nav>header>div>body>html>
效果(不会做点链接弹出demo的效果,会的大神求教): 看效果图:链接元素a的父元素li以及nav元素的高度都是50px,且都为白色背景,但是设置a的css样式为padding:30px之后,发现高度超过了白色区域(即50px),按照行内元素的盒子模型理论,应该是padding-top和padding-bottom都是无效的,然而这里却有效了么?先来看另外一个例子: example2:
DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>example2title><style type="text/css">*{ margin:0px; padding:0px;}span{ color:black; padding:50px; margin:50px; border:3px solid black;}.pone{ color:blue;}.ptwo{ color:tomato;}style>head><body> <p class="pone"> test 1<span>test spanspan>test 1 test 1 test 1 test 1 test 1 test 1 test 1 test 1 test 1 test 1 test 1 test 1 test 1 test 1 test 1 test 1 test 1 test 1 test 1 test 1 test 1 test 1 test 1 test 1 test 1 test 1 test 1 test 1 test 1 p> <p class="ptwo">test 2 test 2 test 2 test 2 test 2 test 2 test 2 test 2 test 2 test 2 test 2 test 2test 2 test 2 test 2 test 2 test 2 test 2 test 2 test 2 test 2 test 2 test 2 test 2 test 2 test 2 test 2 test 2 test 2 test 2p>body>html> 效果: 又是个奇怪的现象,我在截取另一张图,其他都一样,只是test 1部分的数量大量增加: 是的效果如上图,我们可以看到span设置的margin确实符合行内元素的盒子模型,水平方向外边距有效,竖直方向外边距无效,但是对于padding似乎是水平和垂直方向都有效,但我们仔细看上述example1和example2的两张图:example1中,我们设置的padding-top和padding-bottom是相等的,那么如果竖直方向的内边距真的有效,那么content的字体就应该居中,事实上并不是;example2中,我们无视边框的存在,可以看到竖直方向的内边距看不到任何效果,只有水平方向外边距有效。因此,行内元素竖直方向内边距确实是无效的 查w3c的官方文档并没有找到这个奇葩现象解释(可能我英语比较烂,没找到),后来在一篇老外的文章里找到了答案:
这段话基本解释了上述现象,当我们使用内边距时,只有左右方向有效;当我们设置四个方向的内边距时,对于该行内元素,确实显示出效果,但是竖直方向的内边距只有效果,对其他元素无任何影响。 因此,行内元素的padding-top,padding-bottom和margin-top,margin-bottom是真的是无效;不过要注意一点,对于竖直方向的内边距该行内元素的内容范围是增大了,不过只是表象,对周围元素无任何影响。
转载请注明原文地址并标明转载:http://www.cnblogs.com/mingjiezhang/p/5373667.html |
- 上一篇:围住浮动元素的三种方法
- 下一篇:前端新人学习笔记