在CSS中绝对定位的盒子无法通过margin:0 auto;实现水平居中。
正确做法:子盒子通过left属性向右移动父盒子宽度的50%,再通过margin-left负值向左移动自身宽度的50%;
垂直居中同理可得:通过top属性向下移动父盒子高度的一半,再通过margin-top负值向上移动自身个高度的一半。
代码如下:
.father {
/* 给父盒子添加相对定位 */
position: relative;
height: 400px;
width: 600px;
background-color: aquamarine;
margin: 0 auto;
}
.son {
/* 给子盒子添加绝对定位 */
height: 200px;
position: absolute;
width: 300px;
background-color: bisque;
/* 使子盒子水平居中 */
left: 50%;
margin-left: -150px;
/* 使得子盒子垂直居中 */
top: 50%;
margin-top: -100px;
}
效果图:
应用:焦点图制作
如图所示:
要实现此图效果,需要熟练使用定位相关知识:
CSS代码如下:
* {
margin: 0;
padding: 0;
}
li {
list-style: none;
}
.box {
position: relative;
width: 520px;
height: 280px;
background-color: pink;
margin: 100px auto;
}
.box img {
width: 520px;
height: 280px;
}
.left,
.right {
position: absolute;
top: 50%;
margin-top: -15px;
width: 20px;
height: 30px;
background: rgba(0, 0, 0, .3);
text-align: center;
line-height: 30px;
color: #fff;
text-decoration: none;
}
.left {
left: 0;
border-top-right-radius: 15px;
border-bottom-right-radius: 15px;
}
.right {
right: 0;
border-top-left-radius: 15px;
border-bottom-left-radius: 15px;
}
.nav {
position: absolute;
bottom: 15px;
left: 50%;
margin-left: -90px;
width: 180px;
height: 13px;
}
.nav li {
background: #000;
width: 25px;
height: 5px;
display: inline-block;
overflow: hidden;
margin-left: 5px;
cursor: pointer;
}
.nav .selected {
background-color: brown;
}
html代码如下:
<div class="box">
<img src="./images/1.jpg" alt="">
<a href="#" class="left"> < </a>
<a href="#" class="right"> > </a>
<ul class="nav">
<li class="selected"></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>