在图像上居中内容

时间:2017-12-30 01:46:25

标签: html css twitter-bootstrap

我试图将一个自制的字幕集中在图像上,但它的工作效果不太好。我不确定我做错了什么,但这里有一个小提示,显示我正在做的事情:https://jsfiddle.net/efvL28o0/

HTML

<div class= "container-fluid">
<div class="row">
    <div class="col-md-3">
        <a href="" class="rel-tile" >
                <img src="http://via.placeholder.com/1000x500" width="100%">
            <span class="btn-center text-center caption-custom">About Me</span>
        </a>
    </div>
    <div class="col-md-3">
        <a href="" class="rel-tile">
            <img src="http://via.placeholder.com/1000x500" alt="" width="100%">
            <span class="btn-center text-center">Lineage</span>
        </a>
    </div>
    <div class="col-md-3">
        <a href="" class="rel-tile">
            <img src="http://via.placeholder.com/1000x500" alt="" width="100%">
            <span class="btn-center text-center">Contact Me</span>
        </a>
    </div>
    <div class="col-md-3">
        <a href="" class="rel-tile">
            <img src="http://via.placeholder.com/1000x500" alt="" width="100%">
            <span class="btn-center text-center">Gallery</span>
        </a>
    </div>
</div>
</div>

CSS

        .rel-tile {
        position: relative;
    }

    .btn-center {
        position: absolute;
        top: 45%;
        opacity: 0.6;
        left:45%;
        background-color: black;
        color: white;
        text-decoration: none;
    }

理想情况下,无论我为btn-center设置的大小,它都会完全浮在中间。

谢谢!

1 个答案:

答案 0 :(得分:1)

https://jsfiddle.net/bsalex/byqa4qng/3/

.btn-center样式更改为:

.btn-center {
            position: absolute;
            top: 50%;
            opacity: 0.6;
            left:50%;
            background-color: black;
            color: white;
            text-decoration: none;
            transform: translate(-50%, -50%);
        }

这里的主要部分是transform: translate(-50%, -50%); 它是常见的对中技术之一。