简体   繁体   中英

CSS - Stacked elements overflow each other on smaller screens

I have a column of elements each one is below the previous. A simplified version of my code looks like this:

<div style="position: relative; height: 100%;">
   <div style="position: absolute;">Really long text here</div>
   <div style="position: absolute;">Not so long text here</div>
</div>

Basically, my problem is that on smaller screen sizes the first inner div will overflow and will go inside the second div's contents and the texts from both divs will be on top of each other.

How can I prevent this? I wish to display my text in full and yet not allow it to overflow into its neighbouring divs.

<head>    
 <style>
  #mainBox{
   display: flex;
   flex-wrap: wrap;
   justify-content: space-around;
  }
  #mainBox #box1{
   order: 1;
   align-self: flex-start;
   flex-basis: 60%; /*this is the width you wish the div to take*/
  }
  #mainBox #box2{
   order: 2;
   align-self: flex-start;
   flex-basis: 30%;
  }

  /*for smaller screens*/
  @media screen and (max-width: 520px){
    #mainBox{
    display: flex;
    flex-wrap: nowrap;
    flex-direction: column;
   }
  }
 </style>
</head>
<body>
 <div id="firstBox" style="position: relative; height: auto;">
  <div id="box1">Really long text here</div>
  <div id="box2">Not so long text here</div>
 </div>
</body>

with this you will have a responsive layout flexbox has many properties read up on it, its 2018 now a lot of browsers support it, it will save you a lot of time.

position: absolute is going to limit you here unless you want to use some javascript. The idea with position: relative is that elements affect each others' positions -- absolutely positioned elements don't.

Your two best solutions in my mind:

  • position your child elements relatively, then use margin or transform: translate() to shift them around
  • use javascript to reposition sequential elements below each other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM