我有一张图片,根据某些操作可能会改变其位置,并且我想要将几个 div 对象 position
到 img
标签上。
简化的代码如下:
<div>
<img src="someRandomImageUrl">
<div>foobar</div>
</div>
为了更好地理解,假设我有一张图像,在中心某处有一个小正方形,我想让 foobar 消息放置在图像正方形中,无论我将图像放置在何处。有什么想法吗?
我有一张图片,根据某些操作可能会改变其位置,并且我想要将几个 div 对象 position
到 img
标签上。
简化的代码如下:
<div>
<img src="someRandomImageUrl">
<div>foobar</div>
</div>
<div class="container">
<img class="image" src="http://lorempixel.com/400/400" />
<div class="text">foobar</div>
</div>
.container {
position: relative;
display: inline-block;
}
.image { }
.text {
position: absolute;
top: 50%;
left: 50%;
padding: 5px;
margin-top: -14px;
margin-left: -50px;
width: 100px;
background-color: white;
text-align: center;
}
JSFIDDLE DEMO
您可以根据需要调整宽度和边距,将文本居中或定位到您想要的位置。对于 .container
,使用 display: inline-block
可以使 div.container
不跨越整个页面宽度,并允许我们使用绝对定位水平居中。
.container
居中,而不是相对于.image
居中。如果以后向容器添加更多元素怎么办? - morgler.imdesc {
display: inline-block;
vertical-align: middle;
position: relative
}
.imdesc img {
vertical-align: middle;
}
.imdesc p {
text-align: center;
background: #fc0;
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
margin: -50px;
border-radius: 50px;
}
<div class="container-wrap">
<img class="image" src="http://lorempixel.com/400/200/" />
<div class="text-center">foobar</div>
</div>
<div class="container-wrap">
<img class="image" src="http://lorempixel.com/400/200/" />
<div class="text-top">foobar</div>
</div>
<div class="container-wrap">
<img class="image" src="http://lorempixel.com/400/200/" />
<div class="text-bottom">foobar</div>
</div>
.container-wrap {
position: relative;
display: inline-block;
margin:12px 0;
}
.text-center, .text-top, .text-bottom {
position: absolute;
top: 50%;
left: 50%;
padding: 5px;
margin-top: -14px;
margin-left: -50px;
width: 100px;
background-color: white;
text-align: center;
}
.text-top{margin-top:0; top:0;}
.text-bottom{top:auto; bottom:0;}
#botCaptionImage{
position: absolute;
margin-top: 300px; /*usually height of image plus some offset*/
margin-left: -150px;
transform: translateX(-50%); /*Shifts half the width
of caption past the margin-left reference point*/
}
请参考使用translateX的页面
这是HTML代码。 给你一个例子。
<div class="background"
style="background-image: url('../../img/Australia-office_2.png'); height:40%">
<div class="transbox">
<h3>Some text</h3>
<p>
Some text
</p>
</div>
</div>
CSS::
div.background{
background-size: 100% 100%;
}
div.transbox{
color: #000000;
text-shadow: none;
}