[英]Vertically center a header on top of an image
I'm trying to vertically center an h2
on top of an img
, but I can't get it exactly centered. 我试图将h2
在img
上垂直居中,但我无法使其居中。 I'm almost there, but how do I get it exactly there? 我快要到那里了,但是我如何才能准确地到达那里呢?
Details: 细节:
display:table
, but I've tried it and it doesn't play nice with position:relative
and position:absolute
有人建议使用display:table
,但是我已经尝试过了,但它与position:relative
和position:absolute
搭配效果position:absolute
HTML 的HTML
<div class="image">
<img src="http://bit.ly/gUKbAE" />
<div class="wrapper">
<h2>Title</h2>
</div>
</div>
CSS 的CSS
.image {
position: relative;
}
.wrapper {
position: absolute;
top: 50%;
left: 0;
}
h2 {
margin: 0;
padding: 0;
}
I've put it here: http://jsfiddle.net/kmjRu/15/ 我把它放在这里: http : //jsfiddle.net/kmjRu/15/
The reason it is not perfectly centered is because it is making the top
of the line of text at 50%
. 它之所以不能居中,是因为它使文本行的top
占50%
。
Simple fix is changing the line-height
to be 0px
: 简单的解决方法是将line-height
更改为0px
:
.wrapper
{
position: absolute;
top: 50%;
line-height: 0px;
left: 0;
}
Also, if you set the font size of your h2, then you can just add a negative top-margin to your wrapper (or h2 I believe), like so... 另外,如果您设置h2的字体大小,那么您只需向包装器(或我相信的h2)添加负的上边距,就像这样...
.image {
position: relative;
}
.wrapper {
position: absolute;
top: 50%;
left: 0;
margin-top: -15px; /* Set negative margin here to pull it up */
}
h2 {
margin: 0;
padding: 0;
z-index: 2;
font-size: 30; /* Set font size here */
}
I made your h2 font-size 30 and then just set the .wrapper margin-top to -15 here. 我将您的h2字体大小设置为30,然后在此处将.wrapper margin-top设置为-15。
Here it is on jfiddle http://jsfiddle.net/kmjRu/15/ 它在jfiddle上http://jsfiddle.net/kmjRu/15/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.