user400424 user400424 - 5 months ago 9
CSS Question

How to position ::after background image into the center of the div?

I'm trying to position the logo to the center of the header div with half of the logo overflowing to the bottom div. I have the following but I can't figure out how to dynamically set it to be centered. Because relying on

top
and
left
values seems like it's going to be inconsistent.

.header {
position: relative;
height: 200px;
background-color: #000;

&:after {
z-index: 2;
content: ' ';
position: absolute;
left: 27%;
top: 60%;
width: 200px;
height: 200px;
background-image: url('images/logo.png');
}
}

Answer

You can use left: 50% with negative margin-left (half of logo width).

.header {
  background-color: #000;
  position: relative;
  height: 200px;
}

.header:after {
  margin-left: -100px;
  position: absolute;
  background: #f00;
  bottom: -100px;
  height: 200px;
  width: 200px;
  content: ' ';
  z-index: 2;
  left: 50%;
}
<div class="header"></div>