您的位置:首页 > Web前端 > CSS

CSS 小技巧1——水平居中和垂直居中的方法

2015-07-08 13:54 826 查看

一、水平居中的方法

行内元素:最简单的就是加上 text-align:center 属性。

块状元素:

2.1 对于宽度确定的块级元素,可以加上margin: 0 auto ; 属性,这样浏览器就会自动实现水平居中。不过,像分页这种不知道宽度的情况下,这种方法却不怎么适用。

div{
width: 500px;
margin: 0 auto;
background-color: #ff9999;
}


2.2 对于宽度不确定的块级元素,有三种方法可以实现水平居中

加入 table 标签



将块级元素设置成行内元素,再用 text-align属性

用浮动的方法实现水平居中

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>demo</title>
<link rel="stylesheet" href="">
<style type="text/css">
div{
position: relative;
left: 50%;
background-color: #ff9999;
}
</style>
</head>
<body>
<div>
<p>这是一行文本</p>
</div>
</body>
</html>


二、垂直居中的方法

对于单行文本,设置 height 和 line-height 一致

div{
background-color: #ff9999;
height: 500px;
line-height: 500px;
}


对于多行文本,

2.1 将 div 放在 table 标签内,td 标签内的 vertical-align:middle 会实现垂直居中。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>demo</title>
<link rel="stylesheet" href="">
<style type="text/css">
table{
background-color: #ff9999;
height: 500px;
}
</style>
</head>
<body>
<table><tbody><tr><td>
<div>
<p>这是一行文本</p>
<p>这是一行文本</p>
<p>这是一行文本</p>
<p>这是一行文本</p>
</div>
</td></tr></tbody></table>
</body>
</html>


2.2 设置display:table-cell,激活属性,不过这种方法只支持 ie8及以上 chrome、firefox等、

div{
background-color: #ff9999;
height: 500px;
display: table-cell;
vertical-align: middle;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: