简体   繁体   English

垂直和居中对齐文本

[英]Vertically and Center Align Text

I have a h1 within the body and want to vertically align and center align this text. bodyh1 ,并且想要垂直对齐和居中对齐此文本。

I know I can use the position: absolute; 我知道我可以使用以下position: absolute; and then margin-top: "HALF OF HEIGHT"; 然后margin-top: "HALF OF HEIGHT"; but this h1 changes on refresh and has different widths. 但是此h1会在刷新时更改,并且具有不同的宽度。 The height is always the same so I can vertically align it fine but it's center aligning it. 高度始终相同,因此我可以将其垂直对齐,但是将其居中对齐。 I can't use text-align: center; 我不能使用text-align: center; becuase the h1 is positioned absolute so it won't work. 因为h1的位置是绝对的,所以它将无法工作。

Is there an easier way to do this? 有没有更简单的方法可以做到这一点?

Thanks! 谢谢!

Given that the element doesn't have a background, you could do this to horizontally center an element with absolute positioning: 鉴于元素没有背景,您可以执行以下操作以绝对定位使元素水平居中:

.your-element {
    position: absolute;
    width: 100%;
    text-align: center;
}​

A working fiddle: http://jsfiddle.net/VSySg/ 有效的小提琴: http//jsfiddle.net/VSySg/

Depending on the rest of your layout, this may work: 根据布局的其余部分,这可能会起作用:

h1 {
    display: block;
    text-align: center;
    line-height: /* height of container */
}

http://jsfiddle.net/xC3vn/ http://jsfiddle.net/xC3vn/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM