Well, as many said this is a hack. However, I'd like to add more up-to-date hack, which takes an advantage of flexbox
and rem
, i.e.
- You don't want to manually position this text to be changed, that's why you'd like to take an advantage of
flexbox
- You don't want to use
padding
and/or margin
to the text explicitly using px
, which for different screen sizes on different devices and browsers might give different output
Here's the solution, in short flexbox
makes sure that it's automatically positioned perfectly and rem
is more standardized (and automated) alternative for pixels.
CodeSandbox with code below and output in a form of a screenshot, do please read a note
below the code!
h1 {
background-color: green;
color: black;
text-align: center;
visibility: hidden;
}
h1:after {
background-color: silver;
color: yellow;
content: "This is my great text AFTER";
display: flex;
justify-content: center;
margin-top: -2.3rem;
visibility: visible;
}
h1:before {
color: blue;
content: "However, this is a longer text to show this example BEFORE";
display: flex;
justify-content: center;
margin-bottom: -2.3rem;
visibility: visible;
}
Note: for different tags you might need different values of rem
, this one has been justified for h1
and only on large screens. However with @media
you could easily extend this to mobile devices.