简体   繁体   English

在图像上垂直对齐文本

[英]vertical align text on image

I know this question has been asked a lot, but I haven't been able to find a solution among the answers. 我知道这个问题已经问了很多,但是我还没有在答案中找到解决方案。 I'm trying to center a text on an image, but I'm having some trouble with the vertical alignment. 我正在尝试在图像上居中放置文本,但是垂直对齐方式遇到了一些麻烦。 This is my code: 这是我的代码:

<div class="col-sm-12 col-md-12 col-lg-12 main_category_container">
    <div class="col-sm-4 col-md-4 col-lg-4">
        <div class="wrap">
            <h3 class="sub_category_title"><a href="some link">Centered text</a></h3>
            <a href="some link"><img src="some image"></a>
        </div>
    </div>
</div>

and

.wrap {
height:auto;
margin: auto;
text-align:center;
position:relative;
}

h3.sub_category_title {
vertical-align: middle;
}

Right now the text is horizontally centered above the image, but I can't figure out how to vertically align it in the middle of the image. 现在,文本在图像上方水平居中,但我不知道如何在图像中间垂直对齐文本。

Thanks in advance! 提前致谢!

Generally if you're trying to put one element overlapping another, you'll end up using position: absolute or position: relative - otherwise, the contents will naturally arrange themselves in a block flow. 通常,如果您尝试将一个元素与另一个元素重叠,则最终将使用position: absoluteposition: relative否则,内容自然会以块流的形式进行排列。

You could try something like this: 您可以尝试这样的事情:

 .image-wrapper { position: relative; text-align: center; width: 300px; /* change or remove as needed */ margin: auto; } .image-link { display: block; } .image-text { position: absolute; top: 50%; left: 0; right: 0; margin: auto; /* The rest of this is just for this demo, you can change it for your situation. */ font-weight: bold; color: white; font-family: sans-serif; background: rgba(0, 0, 0, 0.5); } 
 <div class="image-wrapper"> <a class="image-link" href="#"> <img class="image" src="http://loremflickr.com/300/200" alt="kitten!"> <h3 class="image-text">A Centered Label</h3> </a> </div> 

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

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