用CSS中心文本div?

时间:2014-08-08 22:32:03

标签: php html css

嘿伙计们试图把这个放在中心位置:

<div class="title" align="center">
<h1>Welcome home, <?php echo ($_SESSION['username'])?>!</h1>
</div>

这是CSS即时使用:

.title{
position: absolute;
margin-left: auto;
margin-right: auto;
}

然而它不起作用,它只是停留在右上方..

提前致谢!

5 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

如果您只想将文本居中于div,请使用:

.title
{
    width: 100%;
    text-align: center;
}

你不需要这个位置。见例:

http://www.cssdesk.com/UAEHe

答案 2 :(得分:0)

http://jsfiddle.net/VerdeletG/tfmkq8bL/

这很简单。只需使用

text-align:center 

用于文字。如果要将内容居中,则创建宽度为100%且margin:auto的容器,然后内容应居中。如果没有,请尝试定位和宽度以及填充和边距。希望它有所帮助!

答案 3 :(得分:0)

当以对应方式集中内容时,我遵循两个基本规则:

一个。对于流体元素

您必须设置宽度(通常为百分比),并使用文本对齐中心。这也适用于img标记内的图像。

<div>Text</div>

div {
    width: 100%;
    text-align: center;
}

湾对于固定宽度的元素

边距自动仅在元素具有固定宽度且相对定位时才有效

<div>Text</div>

div {
    width: 300px;
    margin: 0 auto;
    position: relative;
}

当您必须使用绝对定位来居中元素时:

<div>This</div>

div {
    width: 300px;
    position: absolute;
    left: 50%;
    margin-left: -150px; /*half of width*/
}

答案 4 :(得分:0)

我发现使用此作品可以使div在div内居中

margin: 0;
position: absolute;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%); 

ref:https://www.w3.org/Style/Examples/007/center.en.tmpl