如何将图像文本保持在任何宽度的正中心

时间:2016-04-01 05:52:15

标签: html css css3 twitter-bootstrap-3

您好我正在尝试将文字保留在圆形图像的中心,我尝试使用以下代码它现在是中心但是当我调整窗口大小或将视图更改为ipad时,iphone会向左移动,我们可以管理这个文本确切的中心任何屏幕宽度? 这是我的代码

            <div class="img-div-1 col-md-4 col-sm-4 col-lg-4 col-xs-12">
                <img class="img-circle img-responsive" src="http://placehold.it/250x250" alt="">
                <h4 class="city-name">MONTREAL</h4>
            </div>
            <div class="col-md-4 col-sm-4 col-lg-4 col-xs-12 img-div-2">
                <img class="img-circle img-responsive" src="http://placehold.it/250x250" alt="">
                <h4 class="city-name">PRAGUE</h4>
            </div>
            <div class="col-md-4 col-sm-4 col-lg-4 col-xs-12 img-div-3">
                <img class="img-circle img-responsive" src="http://placehold.it/250x250" alt="">
                <h4 class="city-name">NEW YORK</h4>
            </div>

和css我试过这个是

.city-name{
    font-family: 'open_sansbold';
    font-size: 32px;
    color: white;
    position: absolute;
    top: 50%;
    left: 46%;
    text-align: center;
    /* font-size: 2rem; */
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}

我希望在任何屏幕的中心维护文本,而无需编写自定义代码,例如调整每个屏幕的媒体查询。如果有可能请提供一些建议。非常感谢您访问

这是FiddleDemo

2 个答案:

答案 0 :(得分:0)

请给出以下css:

.img-div-1, .img-div-2, .img-div-3 {
 display: table-cell;
 position: relative;
 width: auto;
}

.city-name左侧属性更改为left: 50%;

并提供h4 margin:0

<强> Working Fiddle

答案 1 :(得分:0)

绝对和相对位置

使用绝对位置时,请注意,您始终需要相对位置来包含它。 所以你的HTML应该是这样的:

<div class="… relative"><!-- Relative position -->
    <img src="example.jpg" alt="">
    <h4 class="city-name">MONTREAL</h4> <!-- Absolute position -->
</div>

你的CSS应该是这样的:(我为每个重要的css规则写了笔记)

div img{ /* This is for image fluid resizing. */
  width: 100%;
  height: auto;
}

.relative{ position: relative; }
.city-name{
    font-family: 'open_sansbold';
    font-size: 32px;
    color: white;
    position: absolute; /* Every absolute position should be contained by a relative position. */
    top: 0; /* Every position is set to 0. */
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 1; /* This will let your text be seen every time. */
    margin: auto; /* Margin will do the trick to center the content. */
    width: 100%; /* Width and Height is needed to let positions center the content. */
    height: 30px;
    text-align: center; /* Text align center because we used width: 100%; so we could writte any size text and it will be centered. */
    line-height: 1em; /* This is not important. */
}

实例:https://jsfiddle.net/w9L44gwL/1/

如果您喜欢我的回答,请选择它来批准。感谢。