position学习终结者(二)

版权声明:本文为博主原创文章。未经博主同意不得转载。 https://blog.csdn.net/wangshuxuncom/article/details/30982863

        在博客《position学习终结者(一)》中我们认识到假设某一absolute作用的元素的父对象(或曾祖父,仅仅要是父级对象)设置了position属性且position的属性值为absolute、relative或者fixed,那么这个子元素会參照离它(指子元素)近期的且position的属性值为absolute、relative或者fixed的父元素进行定位。子元素的定位点为父元素的左上角,学习过padding的人可能会这样想:这个时候假设父元素设置了padding样式,那absolute作用的子元素应该从padding处開始定位吧?呵呵呵。这样的认识对吗,先參见以下的样例:

        代码01:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
		<style type="text/css">
			body{
				margin:0px;
				background-color:gray;
			}
			
			.parent{
				position:absolute;
				margin-left:50px;
				300px;
				height:300px;
				background-color:yellow;
			}
			
			.son1{
				position:absolute;
				left:150px;
				50px;
				height:50px;
				background-color:green;
			}
			
			.son2{
				50px;
				height:50px;
				background-color:red;
			}
		</style>
	</head>
	<body>
		<div class="parent">
			<div class="son1">son1</div>
			<div class="son2">son2</div>
		</div>
	</body>
</html>

图01

        说明:上面的son1父元素没有使用padding样式,这时son1定位点为父元素的左上角;

        代码02

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
		<style type="text/css">
			body{
				margin:0px;
				background-color:gray;
			}
			
			.parent{
				position:absolute;
				margin-left:50px;
				padding-left:50px;
				300px;
				height:300px;
				background-color:yellow;
			}
			
			.son1{
				position:absolute;
				left:150px;
				50px;
				height:50px;
				background-color:green;
			}
			
			.son2{
				50px;
				height:50px;
				background-color:red;
			}
		</style>
	</head>
	<body>
		<div class="parent">
			<div class="son1">son1</div>
			<div class="son2">son2</div>
		</div>
	</body>
</html>

图02

        说明:上面的son1父元素加入了样式padding-left并设置其值为50px

        总结:对照图01和图02我们会发现这样的情况下son1并没有受padding-left的影响。据此我们能够认定父元素纵使设置了padding样式,absolute作用的子元素也是从父元素的左上角開始定位。

        【0分下载演示资源

         【參见还有一篇博客——position学习终结者(一)

原文地址:https://www.cnblogs.com/ldxsuanfa/p/10002832.html