-2

I would like to center a random logo I found ontop of this moving image that scrolls through (jsfiddle doesn't show the moving of the image), but adding <center> tags does not work, and adding margin: auto; works but it doesn't center the image. I am unsure why.

#hb_title {
  background: url('https://cdn.shopify.com/s/files/1/0580/2885/products/the-prison-server-logo_4d5b6eb2-d630-43d9-b8c0-bd024646ef12_400x400.jpg?v=1510041886');
  background-repeat: no-repeat;
  width: 50%;
  margin: auto;
  height: 60%;
}

#header_block {
  background: transparent url('http://i.imgur.com/1tyMljX.jpg') repeat fixed 0% 0%;
  width: 100%;
  height: 139px;
  width: 100% border-bottom: 2px solid #2ECC71;
  text-shadow: 0px 1px 0px rgb(39, 33, 59);
  animation: bganim 20s linear infinite;
}
<div id="header_block">
  <div id="hb_title">
  </div>
</div>

The image does have an adjustable px in the url, and I do realize the image is basic. This is just for practice.

I am also using JSfiddle to test the code.

UncaughtTypeError
  • 6,718
  • 2
  • 17
  • 35
Rhys
  • 81
  • 1
  • 1
  • 7
  • Possible duplicate of [How to horizontally center a
    in another
    ?](https://stackoverflow.com/questions/114543/how-to-horizontally-center-a-div-in-another-div)
    – Temani Afif Jan 07 '18 at 08:02
  • https://stackoverflow.com/questions/1776915/how-to-center-absolutely-positioned-element-in-div – Temani Afif Jan 07 '18 at 08:03
  • https://stackoverflow.com/questions/5703552/css-center-text-horizontally-and-vertically-inside-a-div-block – Temani Afif Jan 07 '18 at 08:03

1 Answers1

1

In CSS3, you can use a little trick. Use position: relative; for the inner box, then set its top: 50%;, and then subtract half the height of your container using transform: translateY(-50%);. Finally, use perspective(1px) to correct the calculation to a whole pixel and prevent issues in some browsers. See the three lines I've added to your CSS:

#hb_title {
  background: url('https://cdn.shopify.com/s/files/1/0580/2885/products/the-prison-server-logo_4d5b6eb2-d630-43d9-b8c0-bd024646ef12_400x400.jpg?v=1510041886');
  background-repeat: no-repeat;
  width: 50%;
  margin: auto;
  height: 60%;
  position: relative;
  top: 50%;
  transform: perspective(1px) translateY(-50%);
}

#header_block {
  background: transparent url('http://i.imgur.com/1tyMljX.jpg') repeat fixed 0% 0%;
  width: 100%;
  height: 139px;
  width: 100% border-bottom: 2px solid #2ECC71;
  text-shadow: 0px 1px 0px rgb(39, 33, 59);
  animation: bganim 20s linear infinite;
}
<div id="header_block">
  <div id="hb_title">
  </div>
</div>
Racil Hilan
  • 22,887
  • 12
  • 43
  • 49