Text not getting printed before my CSS box

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>

>Solution :

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:

<div class="container">
  <p class="box-text">Hello World</p>
  <a class="box"></a>
</div>`
.container {
  position: relative;
}

.box {
  display:flex;
  width:200px;
  height:200px;
  font-size: 2em;
  border:5px solid red;
}

.box-text {
  position: absolute;
  top: -50px;
}

Leave a Reply