Text in absolutely positioned div is overlapping

后端 未结 2 1409
清歌不尽
清歌不尽 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: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%);
    }
    
    
    
      
      
      JS Bin
    
    
     
    Food
    Health

提交回复
热议问题