如何让div内的多行文本上下左右居中

  1、首先,如果div中的文本特别少,不超过div宽度,那么这种就非常简单了,直接line-height等于height就可以了

    <style type="text/css">
            #one{
                width: 200px;
                height: 200px;
                line-height: 200px;
                background: #FF9999;
                text-align: center;
            }
        </style>
        <div id="one">
                我是内容
        </div>

 

2、但是,在文本好多情况下,那么就会出现这种情况

GG了,如果div不是固定高度,使用padding是可以完美实现

    <style type="text/css">
            #one{
                width: 200px;
                padding: 100px 0;
                background: #FF9999;
                text-align: center;
                
            }
        </style>
    </head>
    <body>
            <div id="one">
                我是内容我是内容我是内容我是内容我是内容我是内容我是内容我是内容我是内容我是内容我是内容我是内容
            </div>
    </body>

 

3、2的前提是div不是定高的,但是在很多情况下,我们需要的div是需要定高的,

CSS中的vertical-align属性只会对拥有valign特性的(X)HTML标签起作用,但是在CSS中还有一个display

属性能够模拟<table>,所以我们可以使用这个属性来让<div>模拟<table>就可以使用vertical-align了。注意,display:table和

display:table-cell的使用方法,前者必须设置在父元素上,后者必须设置在子元素上,因此我们要为需要定位的文本再增加一个<div>元素:

<style type="text/css">
.wrap{
display: table;
}
#one{
width: 200px;
height: 200px;
display: table-cell;
background: #FF9999;
text-align: center;
vertical-align: middle;
}
</style>
</head>
<body>
<div class="wrap">
<div id="one">
我是内容我是内容我是内容我是内容我是内容我是内容我是内容我是内容我是内容我是内容我是内容我是内容
</div>
</div>
</body>

 

posted @ 2018-06-07 10:53  伊优  阅读(1151)  评论(0编辑  收藏  举报