Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS how to center ::after pseudo elem

Tags:

html

css

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

like image 274
BeetleJuice Avatar asked Dec 31 '25 21:12

BeetleJuice


2 Answers

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;
    }
}

Compiled CSS version is:

#frame {
    position: fixed;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
    background-color: black;
}

#frame:after {
    position:fixed;
    content: 'Caption overlay';
    color: white;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
    text-align:center;
}
like image 105
Zenel Rrushi Avatar answered Jan 02 '26 11:01

Zenel Rrushi


You could also use svg's own text element along with text-anchor.

Also, what ever the method, white-space: nowrap should keep the text in one line.

<div id="frame">
  <svg width="200" height="200">
    <circle cx="100" cy="100" r="75" stroke="green" stroke-width="15"/>
    <text x="100" y="100" text-anchor="middle">Caption Overlay</text>
  </svg>
</div>

svg:not(:root) {
  overflow: visible;
}
text {
  fill: red;
  white-space: nowrap;
}
like image 29
AA2992 Avatar answered Jan 02 '26 13:01

AA2992