Reputation: 10383
I'm following the solution given in a bagillion places for how to overlay text on an image, using relative
and absolute
positioning. The problem is that the text with position: absolute
pops out of its container and goes to the utmost top
, right
, etc.
I'd be happy to use a background image, but then I need tricks to get the container to match the size of the image, and I don't know of a way to make it fluid.
Seems like a pretty simple problem that folks are always looking for a solution to. Also the thing of overlaying text on an opaque image, and needing to use :after
. Wish there were straightforward options for these situations.
.container {
margin: 0 10%;
}
.container img {
position: relative;
width: 100%;
}
#div1 .text {
position: absolute;
bottom: 0;
right: 0;
}
#div2 .text {
position: absolute;
top: 0;
left: 0;
}
<div id="div1" class="container">
<img src="http://placehold.it/800x200" />
<div class="text">
<h3>Top Image</h3>
<p>This text should be in the bottom right of the top image.</p>
</div>
</div>
<div><p>A bunch of miscellaneous text here.</p></div>
<div id="div2" class="container">
<img src="http://placehold.it/800x200" />
<div class="text">
<h3>Lower Image</h3>
<p>This should be in the top left of the lower image.</p>
</div>
</div>
Upvotes: 2
Views: 1378
Reputation: 1
I am not quite sure there is enough information. I am assuming that your containers are 800px wide and 200 px tall (I have used a min-height in case your container increases its height). If you could provide more specific information that would be great (there are more complicated ways using object-position property (etc) to make this a little bit "smarter".
img {
max-width: 100%;
display: block;
height: auto;
}
.container {
position: relative;
min-height: 200px;
width: 800px;
margin: 0 10%;
}
.container img {
z-index: 500;
top: 0;
left: 0;
}
.container .text {
position: absolute;
z-index: 1000;
}
#div1 .text {
bottom: 0;
right: 0;
}
#div2 .text {
position: absolute;
top: 0;
left: 0;
}
Upvotes: 0
Reputation: 2676
You need to set position:relative
on .container
which is the correct container for .text
. Note that the img
is a sibling of .text
and not its container.
.container {
margin: 0 10%;
position: relative;
}
.container img {
width: 100%;
}
#div1 .text {
position: absolute;
bottom: 0;
right: 0;
}
#div2 .text {
position: absolute;
top: 0;
left: 0;
}
<div id="div1" class="container">
<img src="http://placehold.it/800x200" />
<div class="text">
<h3>Top Image</h3>
<p>This text should be in the bottom right of the top image.</p>
</div>
</div>
<div><p>A bunch of miscellaneous text here.</p></div>
<div id="div2" class="container">
<img src="http://placehold.it/800x200" />
<div class="text">
<h3>Lower Image</h3>
<p>This should be in the top left of the lower image.</p>
</div>
</div>
Upvotes: 2