Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

responsive image centered on top of another responsive image

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%;
}
like image 743
ScreamQueen Avatar asked Sep 02 '25 02:09

ScreamQueen


2 Answers

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>
like image 86
d-h-e Avatar answered Sep 04 '25 15:09

d-h-e


This is not a bad solution per se, but you would make it easier on yourself if:

  • You would use background-image: src("url_here") instead of the background element (so remove that DOM node and attach the CSS to .container
  • center the second div inside it using 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.

like image 29
Billie Bobbel Avatar answered Sep 04 '25 16:09

Billie Bobbel