CSS加了定位的盒子如何水平居中、垂直剧中
1.定位盒子的剧中定位的实现
2.案例-轮播图布局
1.绝对定位的盒子居中
要知道加了定位的盒子使用margin:auto来布置盒子居中时无法实现的,需要用到一个小小的算法。
直接用一个例子来说明:
实现效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
position: absolute;
/* 调整水平居中,先左移50%的宽度,在用外边框调整至自身盒子一半的距离,实现居中 */
left: 50%;
margin-left: -100px;
/* 垂直居中同理 */
top: 50%;
margin-top: -100px;
width: 200px;
height: 200px;
background-color: thistle;
}
</style>
</head>
<body>
<div class="box"></div>
</div>
</body>
</html>
相对定位由于是不脱离标准流的,所以可以直接使用margin auto;这个太简单的就不举例子了。
2.案例-轮播图布局
实现效果:
轮播图.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>轮播图</title>
<link rel="stylesheet" href="轮播图.css">
</head>
<body>
<div class="tb-b">
<img src="imgs/tb.jpg">
<a href="#" class="left">
< </a>
<a href="#" class="right"> > </a>
<ul class="nav">
<li> </li>
<li></li>
<li></li>
<li></li>
<li class="last"></li>
</ul>
</div>
</body>
</html>
轮播图.css
* {
margin: 0;
padding: 0;
}
li {
list-style: none;
}
.tb-b {
position: relative;
margin: 100px auto;
width: 530px;
height: 290px;
background: pink;
text-align: center;
}
img {
margin: 5px auto;
}
.left,
.right {
margin-top: -15px;
display: block;
width: 20px;
height: 30px;
text-align: center;
line-height: 30px;
background-color: rgba(0, 0, 0, 0.3);
text-decoration: none;
color: white;
}
.left {
position: absolute;
top: 50%;
left: 5px;
border-radius: 0 15px 15px 0;
}
.right {
position: absolute;
top: 50%;
left: 505px;
border-radius: 15px 0 0 15px;
}
.nav {
position: absolute;
bottom: 10px;
left: 50%;
margin-left: -30px;
width: 70px;
height: 13px;
background-color: rgba(255, 255, 255, 0.3);
border-radius: 6.5px;
}
li {
width: 8px;
height: 8px;
float: left;
margin: 3px;
border-radius: 4px;
background-color: white;
text-align: center;
}
ul .last {
margin-right: 0px;
}
li:hover {
background-color: tomato;
}