I am not getting the concept as to why in my snippet Hello World
get printed inside the box rather than before the box (as I used .box::before
)? I tried some docs but they were unhelpful.
.box {
display:flex;
width:200px;
height:200px;
font-size: 2em;
border:5px solid red;
}
.box::before {
content: 'Hello World';
}
<a class="box"></a>
3
Answers
The reason why the text "Hello World" appears inside the box instead of before it is because of the CSS property content that you used in the pseudo-element ::before.
When you use the content property, it creates a pseudo-element that is inserted before the content of the selected element (.box in this case). In other words, it creates an imaginary element that sits before the .box element and has the content "Hello World".
Since the .box element is empty, the "Hello World" text that you specified using content becomes the content of the .box element. And since the .box element has a border, the text appears inside the border.
If you want the "Hello World" text to appear before the .box element, you can use the ::before pseudo-element on a different element, such as a div or a p element, and position it before the .box element using CSS. For example:
I think this is more what you’re looking for. There may be a better way to do it with a class but this is how I’ve done it
The pseudo-elements generated by
::before
and::after
are contained by the element’s formatting box. Check this documentation for more info on this.