一.css如何设置元素在垂直居中
当我们希望容器中的元素在垂直方向进行剧中时,我们通常可以通过如下两种方式实现,例如如下案例:
1.1 使用position定位
我们希望输入框和点击按钮在长方形容器进行垂直居中,这时候进行如下设置
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=Edge">
<title>test</title>
<style>
#out {
position: relative;
}
#out span {
position: absolute;
top:50%;
left:0;
transform: translate(0, -50%)
}
</style>
</head>
<body>
<div id="container" style="width: 60%;height: 100px;margin: 50px auto;">
<div id="out" style="width: 60%;height: 40px;border: 1px solid #000;">
<span>
<label for="one"></label>
<input type="text" id="one" placeholder="请输入内容">
<button style="padding: 5px auto;">点击</button>
</span>
</div>
</div>
</body>
<script>
</script>
</html>
我们设置id="out"的容器设置定位,然后设置下面的span内容绝对定位,然后设置离顶部的距离为50%,最后设置垂直方向移动的高度为本身高度的-50%即可让其居中