垂直和水平居中文本在图像上 [英] Vertically and horizontally centering text over an image
问题描述
我想要一个宽度为100%,高度约为屏幕的70%的大图片。在这个图像上,我想在这个图像的顶部有一些文本,这个文本需要在图像的中间向右。 总而言之:如何在100%宽的图片中水平和垂直放置此文字?:
I want to have a big image that has a width of 100% and a height of about 70% of the screen. On this image I want some text ontop of this image and this text needs to go right in the middle of the image. In a nutshell: how can I center horizontal and vertical this text in a 100% width image?:
<div id="top-area">
<img src="img/startphoto.jpg" alt="background image #1" />
<p>Some text</p>
</div>
#top-area img{
width: 100%;
position: absolute;
top: 0px;
left: 0px;
}
#top-area p{
position: relative;
text-align: center;
margin-top: 330px;
color: white;
font-family: 'Montserrat', sans-serif;
font-size: 3em;
}
我知道我使用margin-top获取文本的水平位置,但这感觉就像错误的方式。
I know I use margin-top to get the horizontal place of the text, but this feels like the wrong way. Anyone got beter suggestions?
推荐答案
您可以指定 position:absolute
元素 img
和 p
。然后,您可以在 p
元素上声明 top:40%;
我使用 40%
的原因是由于您使用的文字的大小。您可以使用 50%
,然后使用javascript计算文本的高度,并为其指定顶部负边距。只有在您的文字高度动态变化时才需要。
You could assign position:absolute
to the img
and p
element. You would then declare top:40%;
on the p
element to vertical centralise it. The reason I use 40%
is due to the size of the text you're using. You could use 50%
and then with javascript calculate the height of the text and assign a top negative margin to it. This is only required if your text height will vary dynamically.
DEMO http://jsfiddle.net/fRbNe/
html, body {
height: 100%;
}
#top-area {
position: relative;
height: 70%;
width:100%;
}
#top-area img {
width: 100%;
height: 100%;
position: absolute;
top: 0px;
left: 0px;
}
#top-area p {
margin:0;
padding:0;
text-align: center;
top:40%;
height: 100%;
width:100%;
position: absolute;
color: white;
font-family:'Montserrat', sans-serif;
font-size: 3em;
}
这篇关于垂直和水平居中文本在图像上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!