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

来源:互联网 发布:北京优化 编辑:程序博客网 时间:2024/06/06 08:43

代码如下

<!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>

效果如下

这里写图片描述

0 0
原创粉丝点击