您的位置:首页 > 其它

容器,文字的水平和垂直居中的方法

2017-03-10 11:14 162 查看

代码如下

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
<style type="text/css">
#container{
width: 500px;
height: 500px;
background-color: blue;
margin: 0 auto;         /*容器本身水平居中,不继承*/
text-align: center;     /*容器内文字水平居中,可继承*/
position: relative;
}
#wrapper{
width: 300px;
height: 200px;
background-color: yellow;
position: absolute;
top: 50%;
margin-top: -100px;
/*设置为容器的负1/2高度,不能用百分比,因为那样是相对父容器的。*/
/*动态容器高度则用js获取后修改*/
}
#word{
width: 200px;
height: 100px;
line-height: 100px;     /*单行文本行高等于容器高*/
background-color: green;
color: pink;
margin: 0 auto;         /*只能水平居中*/
}
#test2{
width: 300px;
height: 300px;
background-color: orange;
text-align: center;
display: table-cell;    /*配合vertical-align,ie7及以下不兼容*/
vertical-align: middle;
}
#more-lines{
background-color: yellow;
}
</style>
</head>
<body>
<div id="container">
<div id="wrapper">
<p id="word">Only one line.</p>
</div>
</div>
<div id="test2">
<p id="more-lines">
Much more lines.Much more lines.Much more lines.Much more lines.Much more lines.Much more lines.Much more lines.Much more lines.
</p>
</div>
</body>
</html>


效果如下

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: