skip to Main Content

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


  1. 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;
    }
    
    Login or Signup to reply.
  2. .box {
        display:flex;
        width:200px;
        height:200px;
        font-size: 2em;
        border:5px solid red;
    }
    b::before {
    content: 'Hello World';
    }
       <b> <a class="box"></a></b>

    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

    Login or Signup to reply.
  3. The pseudo-elements generated by ::before and ::after are contained by the element’s formatting box. Check this documentation for more info on this.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search