css margin-top属性不起作用的几个原因

WBOY
Release: 2016-06-01 09:53:31
Original
7403 people have browsed it

原因一:
外边距合并margin-top属性失效。代码实例如下:

<code class="language-html">


<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="author" content="http://www.softwhy.com/">
<title>蚂蚁部落</title>
<style type="text/css">
.first{
  width:100px;
  height:100px;
  background-color:red;
  margin-bottom:60px;
}
.second{
  width:100px;
  height:100px;
  background-color:green;
  margin-top:40px;
}
</style>


<div class="first"></div>
<div class="second"></div>

</code>
Copy after login

从以上代码的运行可以看出,第二个div设置的margin-top并没有生效,起作用的是第一个div的设置的margin-bottom,这里有个规律,那就是合并后的外边距的高度等于外边距的高度中的较大的一个,所以遇到此种情况可以格外注意外边距大小的设置。

 

原因二:
子元素和父元素也可能会导致设置的子元素上外边距失效情况,代码实例如下:

<code class="language-html">


<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="author" content="http://www.softwhy.com/">
<title>蚂蚁部落</title>
<style type="text/css">
.father{
  width:300px;
  height:300px;
  background-color:red;
  margin-top:20px;
}
.children{
  width:100px;
  height:100px;
  background-color:blue;
  margin-top:10px;
}
</style>


<div class="father">
  <div class="children"></div>
</div>

</code>
Copy after login

解决方法:
为父对象在相应的外边距方向上有边框(border)和内边距(padding),或者为overflow属性值设置为hidden即可避免。
IE6浏览器下不会出现外边距合并现象。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template