BeetleJuice
BeetleJuice

Reputation: 40886

CSS how to center ::after pseudo elem

I'm having trouble centering an ::after CSS pseudo element. The main element is an 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

Upvotes: 3

Views: 14977

Answers (3)

Zenel Rrushi
Zenel Rrushi

Reputation: 2366

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

Upvotes: 10

AA2992
AA2992

Reputation: 1607

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

Upvotes: 2

frnt
frnt

Reputation: 8795

Add position:absolute to your ::after pseudo element.

 &:after {
    position:absolute;
    width:100%;
    text-align:center;
    ........
    ........
  }

Upvotes: 1

Related Questions