在WEB开发中,经常需要对元素居中排列,包括水平居中和垂直居中。下面分情况说明各种常见的CSS居中操作。
1、对于文字来说
文字水平居中,使用
text-align: center;
如果我们希望一行文字水平垂直都居中显示在屏幕中央:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>居中</title>
<style>
html,body{
height: 100%;
width: 100%;
background-color: aqua;
overflow: hidden;
}
.box{
text-align: center;
line-height: 100vh;/*这里使用了CSS3中新增的vh单位,代表行高是屏幕高度*/
}
</style>
</head>
<body>
<div>wanmait.com</div>
</body>
</html>当然这种情况只能是一行文字,多行就会出问题。

如果多行文字,我们放入到一个div中,可以如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>居中</title>
<style>
*{
padding: 0;
margin: 0;
}
html,body{
height: 100%;
width: 100%;
background-color: aqua;
overflow: hidden;
}
.box{
text-align: center;
width: 300px;
top:0;
bottom: 0;
left: 0;
right: 0;
margin:auto;
background-color: white;
padding: 20px;
position: absolute;
height: 50px;
}
</style>
</head>
<body>
<div>
<p>万码学堂</p>
<p>wanmait.com</p>
</div>
</body>
</html>
2、使用flex弹性布局
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>居中</title>
<style>
*{
padding: 0;
margin: 0;
}
html,body{
height: 100%;
width: 100%;
background-color: aqua;
overflow: hidden;
}
body{
display: flex;/*body设置为弹性布局*/
align-items: center;
justify-content: center;
}
.box{
text-align: center;
width: 300px;
background-color: white;
padding: 20px;
height: 50px;
}
</style>
</head>
<body>
<div>
<p>万码学堂</p>
<p>wanmait.com</p>
</div>
</body>
</html>

0条评论
点击登录参与评论