1、子绝父相
如图所示的导航条,是通过相对定位与绝对定位共同完成的。
在仅使用相对定位的情况下,由于相对定位在标准流中仍然占有一定的空间,会对页面布局产生不良的影响,所以不能仅仅使用相对定位。
所以父标签使用相对定位,而子标签则使用绝对标签,这样既不会对页面布局产生不良的影响,又可以更方便的进行布局。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>标题</title>
<style>
* {
margin: 0;
padding: 0;
}
ul {
list-style: none;
width: 800px;
height: 30px;
margin: 0 auto;
margin-top: 100px;
}
ul li {
float: left;
text-align: center;
line-height: 30px;
width: 100px;
background-color: #ccc;
}
.c1 {
background-color: red;
position: relative;
}
.c1 img {
position: absolute;
top: -15px;
left: 35px;
}
</style>
</head>
<body>
<ul>
<li>服装城</li>
<li>美妆馆</li>
<li>京东超市</li>
<li class="c1">全球购
<img src="导航.jpg" height="20px" width="20px">
</li>
<li>闪购</li>
<li>团购</li>
<li>拍卖</li>
<li>金融</li>
</ul>
</body>
</html>
2、水平居中
width: 50%,代表着把宽度变为浏览器当前页面宽度的一半,不论页面大或是小,均为当前页面宽度的一半。
将绝对定位元素居中:
left: 50%;
margin-left: -元素宽度的一半
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>标题</title>
<style>
* {
margin: 0;
padding: 0;
}
.c1 {
height: 200px;
width: 400px;
background-color: blue;
position: absolute;
left: 50%;
margin-left: -200px;
}
</style>
</head>
<body>
<div class="c1"></div>
</body>
</html>