如何将一个div相对于一张图片进行定位?

4

我有一张图片,根据某些操作可能会改变其位置,并且我想要将几个 div 对象 positionimg 标签上。

简化的代码如下:

<div>
    <img src="someRandomImageUrl">
    <div>foobar</div>
</div>

为了更好地理解,假设我有一张图像,在中心某处有一个小正方形,我想让 foobar 消息放置在图像正方形中,无论我将图像放置在何处。有什么想法吗?

3
图片不能包含一个 div;请将两个项目放到一个 div 中,并对该 div 进行定位。 - Salman A
你的意思是“foobar”消息应该放在图片的顶部吗? - aniskhan001
5个回答

5
你可以尝试使用绝对定位来设置 "foobar":
<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 不跨越整个页面宽度,并允许我们使用绝对定位水平居中。


1
这样做会将div相对于.container居中,而不是相对于.image居中。如果以后向容器添加更多元素怎么办? - morgler

2
像这样吗?http://jsfiddle.net/q0so8esf/
.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;
}

0
<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;}

0
您可以尝试使用translateX(-50%),并结合必要的margin-left或margin-right来使您想让其相对于图像居中的元素居中。
#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的页面


-1

这是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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接