Text in absolutely positioned div is overlapping

后端 未结 2 1407
清歌不尽
清歌不尽 2021-01-28 07:50

In the below code snippet, the div elements (.main > div) are relatively positioned and are floated left.

Because of the relative positioning, the div elements (.main >

相关标签:
2条回答
  • 2021-01-28 08:16

    The reason is that each of your position:absolute; elements are removed from the DOM's native flow, and positioned absolutely to their parent element. Since they both have the same positioning, they are placed over top of each other. Use position:relative to position the elements relative to their native position in the DOM.

    0 讨论(0)
  • 2021-01-28 08:26

    Your understanding is correct, though in this case where the div's is floated, they will collapse into a width of 0, as none of the div's has any normal flowing content, hence your absolute span's overlap.

    In below sample I gave the div's a width, and now you can see it works how you expected.

    html, body {
      width: 100%;
      height: 100%;
    }
    
    .main {
      height: 5%;
      border: 1px solid thistle;
    }
    
    .main > div {
      position: relative;
      float: left;
      height: 100%;
      border: 1px solid black;
      width: 100px;                 /*  added a width  */
    }
    
    
    .main > div > span {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
    }
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>JS Bin</title>
    </head>
    <body>
     <div class="main">
       <div><span>Food</span></div>
       <div><span>Health</span></div>
     </div>
    </body>
    </html>

    0 讨论(0)
提交回复
热议问题