CSS文字垂直居中

html-css06

CSS文字垂直居中,第1张

01

先写上html代码,如图,内容很简单,就是一个div里有一段文本。

02

再写上div对应的样式,如图,这里只设置了div的边框和高度,宽度。

03

如果这里显示的话,我们看下页面,文本是不会水平居中和垂直居中的。

04

要让文本水平居中,我们可以添加样式:text-align: center

要让文本垂直居中,我们可以添加样式: vertical-align: middle和display: table-cell

05

添加完这几个样式后,刷新页面可以看到现在的文本已经可水平居中和垂直居中了。

你说的文字居于底部是指浏览器底部么,如果是的话,需要用到CSS属性position,而position: fixed就是相对于浏览器进行定位的,让后用left, right, bottom, top这些坐标值来进行指定位置,底部就是bottom: 0,所以让文字垂直居底就像下面这个例子一样:

<!doctype html>

<html lang="en">

    <head>

        <meta charset="UTF-8">

        <title>Document</title>

        <style>

            #footer{

                position: fixed

                bottom: 0

                width: 100%

                text-align: center

            }

        </style>

    </head>

    <body>

        <div id="footer">垂直居于底部的文字</div>

    </body>

</html>

这个例子里还假设你是除了需要垂直居底以外,还需要居中设置,因此那个width:100%和text-align: center就是为了居中放置的,这种设置经常用在一个网站用于声明版权、网站地图这些,多看几个这样的网站源代码就会发现,它们都是这么做的。

此外,还有一个position: absolute,生成绝对定位的元素,相对于 static 定位以外的第一个父元素进行定位。元素的位置还是通过 "left", "top", "right" 以及 "bottom" 属性进行规定。你可以拿它来做到让某个元素处于一个区域比如某个div背景的底部,这时外面套的那个元素不能用默认的positon设定,需改成position: relative。例如:

<!doctype html>

<html lang="en">

    <head>

    <meta charset="UTF-8">

    <title>Document</title>

    <style>

        #container{

            position: relative

            width: 400px

            height: 300px

            margin: 20px auto

            background-color: #de5

        }

        #innerFooter{

            position: absolute

            bottom: 0

            width: 100%

            text-align: center

        }

    </style>

    </head>

    <body>

        <div id="container">

            <div id="innerFooter">始终垂直居于块元素底部的文字</div>

        </div>

    </body>

</html>

div+css实现文字垂直居中的五种方法:

1、把文字放到table中,用vertical-align property 属性来实现居中。

<div id="wrapper">

<div id="cell">

<div class="content">Content goes here</div>

</div>

</div>

2、使用绝对定位的 div,把它的 top 设置为 50%,top margin 设置为负的 content 高度。这意味着对象必须在 CSS 中指定固定的高度。

#content {

position: absolute

top: 50%

height: 240px

margin-top: -120px/* negative half of the height */

}

<div class="content">Content goes here</div>

3、在 content 元素外插入一个 div。设置此 div height:50%margin-bottom:-contentheight。

content 清除浮动,并显示在中间。

<div id="floater">

<div id="content">Content here</div>

</div>

#floater {

float: left

height: 50%

margin-bottom: -120px

}

#content {

clear: both

height: 240px

position: relative

}

4、使用 position:absolute,有固定宽度和高度的 div。这个 div被设置为 top:0bottom:0。但是因为它有固定高度,其实并不能和上下都间距为 0,因此 margin:auto会使它居中。使用 margin:auto使块级元素垂直居中即可

<div id="content">Content here</div>

#content {

position: absolute

top: 0

bottom: 0

left: 0

right: 0

margin: auto

height: 240px

width: 70%

}

5、将单行文本置中。只需要简单地把 line-height 设置为那个对象的 height 值就可以使文本居中了。

<div id="content">Content here</div>

#content {

height: 100px

line-height: 100px

}