I'm having trouble centering an ::after CSS pseudo element. The main element is an image:
::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
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;
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With