BeetleJuice BeetleJuice - 2 months ago 7
CSS Question

CSS how to center ::after pseudo elem

I'm having trouble centering an

::after
CSS pseudo element. The main element is an image:


  • the image should be in the center of the page

  • the
    ::after
    pseudo element which shows the image caption, should be overlaid in the center of the image.



Here is what I have:



#frame {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: black;
&: after {
content: 'Caption overlay';
color: white;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
}

<div id="frame">
<svg width="200" height="200">...</svg>
</div>





The image frame is correctly centered on the page, but its caption is not centered over the image. Instead it is at the bottom right corner.

Codepen

Answer

You can do it by adding text-align:center; and also position: fixed; to your :after pseudo element.

#frame {
  position: fixed;
  top:50%;
  left:50%;
  transform:translate(-50%,-50%);
  background-color: black;
  &:after {
    position:fixed;
    content: 'Caption overlay';
    color: white;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
    text-align:center;
  }
}
Comments