skip to Main Content

When applying a negative margin to an element why the text 1 over the background of child 2 and behind the text , i thought it will be behind the whole box.

html {
  font-size: 40px;
  font-weight: bold;
}

.child1 {
  color: white;
  background-color: red;
}

.child2 {
  color: black;
  background-color: green;
  margin: -35px 0 0 20px;
}
<body>
  <div>
    <div class="child1">text 1 some text here</div>
    <div class="child2">text 2 other text here</div>
  </div>
</body>

2

Answers


  1. <!DOCTYPE html>
    <html>
    <head>
    <style>
      html {
        font-size: 40px;
        font-weight: bold;
      }
    
      .child1 {
        color: white;
        background-color: red;
        position: relative; /* Create stacking context */
        z-index: 2; /* Ensure it is above .child2 */
      }
    
      .child2 {
        color: black;
        background-color: green;
        margin: -35px 0 0 20px;
        position: relative; /* Ensure it is part of stacking context */
        z-index: 1; /* Ensure it is below .child1 */
      }
    </style>
    </head>
    <body>
      <div>
        <div class="child1">text 1 some text here</div>
        <div class="child2">text 2 other text here</div>
      </div>
    </body>
    </html>
    
    Login or Signup to reply.
  2. You can simply make the whole .child2 box move over the .child1 elt using css z-index property:

    .child2 {
      ...
      position: relative;
      z-index: 2;
    }
    

    Full example:

    html {
      font-size: 40px;
      font-weight: bold;
    }
    
    .child1 {
      color: white;
      background-color: red;
    }
    
    .child2 {
      color: black;
      background-color: green;
      margin: -35px 0 0 20px;
      position: relative;
      z-index: 2;
    }
    <body>
      <div>
        <div class="child1">text 1 some text here</div>
        <div class="child2">text 2 other text here</div>
      </div>
    </body>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search