-1

I have a div with a background image that is always supposed to have the same aspect ratio no matter the screen resolution. I set this with:

padding-top: 50%;

Now, inside that div I am trying to center (equal top and bottom, left and right) an image, also no matter what the resolution. I achieve this with:

left: 50%;
display: inline-block;
transform: translate(-50%,0);
position: absolute;
z-index: 1;
top:50px;

Now, that all works, except the image is not centered vertically as the browser resizes. It moves up and down.

How do I achieve it to align vertically in the middle as well? I suspect I have to remove the top:50px but then I am stuck on how to center it..

Here is a fiddle: https://jsfiddle.net/fjLo7egd/1/

moo moo
  • 476
  • 5
  • 20

3 Answers3

1

Please try this:

.logo{
    left: 50%;
    display: inline-block;
    transform: translate(-50%,-50%);
    position: absolute;
    z-index: 1;
    top:50%;
    max-width:100px;
}
Joykal Infotech
  • 1,840
  • 3
  • 9
  • 17
1

Please try this:

 .logo{
    position: absolute;
    top:0;
    bottom: 0;
    right: 0;
    left: 0;
    margin: auto;
    max-width: 100px;
}
Eugen Govorun
  • 3,006
  • 1
  • 11
  • 12
0

change top:50px to top:50% and remove margin: 0 auto;

.background {
  width: 100%;
  overflow: hidden;
  background-color: #FFFFFF;
  margin-bottom: 0px;
  background-position-x: 50%;
  background-position-y: 50%;
  background-repeat-x: no-repeat;
  background-repeat-y: no-repeat;
  background-attachment: local;
  background-size: cover;
  display: block;
  position: relative;
  background-color: #f4f4f4;
  padding-top: 50%;
  text-align: center;
  border: 5px solid #c4c4c4;
  background-image: url(https://upload.wikimedia.org/wikipedia/commons/thumb/6/6d/City_of_London_skyline_from_London_City_Hall_-_Sept_2015_-_Crop_Aligned.jpg/1200px-City_of_London_skyline_from_London_City_Hall_-_Sept_2015_-_Crop_Aligned.jpg);
}

.logo {
  left: 50%;
  display: inline-block;
  transform: translate(-50%, 0);
  position: absolute;
  z-index: 1;
  top: 50%;
  max-width: 100px;
}
<div class="background">
  <img class="logo" src="https://seeklogo.com/images/U/underground-london-logo-0B52F46982-seeklogo.com.png">
</div>
Xenio Gracias
  • 2,728
  • 1
  • 9
  • 16