gpt4 book ai didi

html - 如何在任何宽度的情况下使图像上的文本恰好位于中心

转载 作者:行者123 更新时间:2023-11-28 06:08:00 24 4
gpt4 key购买 nike

您好,我试图将文本保持在圆圈图像的中心,我已经尝试使用以下代码它现在位于中心但是当我调整窗口大小或将 View 更改为 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

最佳答案

绝对和相对位置

在使用绝对 位置时,请记住您始终需要一个相对 位置来包含它。所以你的 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/

如果喜欢我的回答,请点赞。谢谢。

关于html - 如何在任何宽度的情况下使图像上的文本恰好位于中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36348989/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com