1. 水平垂直居中(css3):

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>布局实验</title>
<style>
.container{
top: 100px;
width: 100%;
height: 200px;
background-color: antiquewhite;
text-align: center;
}
.container .box{
position: relative;
width: 200px;
height: 100px;
background-color: aqua;
font-size: 12px;
border: 1px solid #000;
display: inline-block;
top: 50%;
transform: translateY(-50%);
}
</style>
</head>
<body>
<!--水平居中-->
<div class="container">
<div class="box">text-align center方式</div>
<div class="box">text-align center方式</div>
<div class="box">text-align center方式</div>
</div>
</body>
</html>
知识点:
-
水平居中:行内元素居中是只针对行内元素的,比如文本(text)、图片(img)、按钮等行内元素,可通过给父元素设置 text-align:center 来实现。另外,如果块状元素属性display 被设置为inline时,也是可以使用这种方法。但有个首要条件是子元素必须没有被float影响,否则一切都是无用功。
-
垂直居中:使用top和transform: translateY(-50%);实现。top:50%;表示box的上边缘距离父元素上边缘为父元素高度的50%,translateY(-50%)则表示向上偏移box高度的50%。
2. css2下居中:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>css居中</title>
<style>
body{
margin: 0;
padding: 0;
}
.container {
width: 100%;
height: 500px;
background-color: antiquewhite;
overflow: hidden;
}
.container .box-container {
position: relative;
top: 50%;
width: 620px;
height: 100px;
margin: 0 auto;
margin-top: -100px;
background-color:aquamarine;
}
.container .box {
position: relative;
width: 200px;
height: 100px;
box-sizing: border-box;
background-color: aqua;
font-size: 12px;
border: 1px solid #000;
display: block;
float: left;
text-align: center;
line-height: 100px;
}
.mr{
margin-right: 10px;
}
</style>
</head>
<body>
<!--水平垂直居中-->
<div class="container">
<div class="box-container">
<div class="box mr">css2居中方式</div>
<div class="box mr">css2居中方式</div>
<div class="box">css2居中方式</div>
</div>
</div>
</body>
</html>

本文详细介绍了使用CSS3和CSS2实现元素水平垂直居中的方法。对于CSS3,通过设置top属性和transform的translateY来实现;对于CSS2,则利用相对定位和负margin来达到目的。这些技巧适用于网页设计中的各种布局需求。
1万+

被折叠的 条评论
为什么被折叠?



