I just cannot figure out the best way to get a responsive image to sit in the center of another responsive image.
Right now, I have a responsive image, with another image absolutely positioned and centered on top. When I try to set a width for this second image, it is no longer centered.
Also when I resize the window, this centered element expands outside the the parent. Is there a way to keep it contained? Do I have this all wrong and is there a better way to achieve this?
What can I do?
Thanks
Here is a fiddle
<div class="container">
<img class="background" src="https://via.placeholder.com/560x500/FFFF00/">
<div class="logo"><img src="https://via.placeholder.com/300x120"></div>
</div>
.container{
position: relative;
}
.container .logo {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.container .background {
width: 100%;
}
You can use flexbox for centering.
.container {
position: relative;
display: flex;
justify-content: center;
align-items: center;
}
.container .logo {
position: absolute;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
/* size of second image */
.container .logo>img {
width: 100px;
}
.container .background {
width: 100%;
}
<div class="container">
<img class="background" src="https://via.placeholder.com/560x500/FFFF00/">
<div class="logo"><img src="https://via.placeholder.com/300x120"></div>
</div>
This is not a bad solution per se, but you would make it easier on yourself if:
background-image: src("url_here")
instead of the background
element (so remove that DOM node and attach the CSS to .container
margin: 0 auto;
or margin: auto;
(if it's a block
element and has width/height)That should prevents some of the issues you're facing and would remove the entire need for the absolute positioning and transform. However making the second image grow bigger than the container it's in would become an issue (since it's no longer outside of the constraints of the parent).
This can obviously also be done with Flexbox or any other layout method. But this is the most basic way to achieve this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With