htmlcssresponsiveness

How to make a div with lengthy text values responsive without overflowing parent element boundries


I'm trying to make the .right element flexible so that it can expand or contract to fill the remaining parent width without exceeding it or causing the .icon to go outside of the parent elements border. It needs to be responsive as the width will change depending on mobile device orientation. As you can see with my current code, it causes over flow of the parent element.

Is this possible using just plain HTML/CSS? (no libraries)

section {
  display: flex;
  border: 3px solid red;
  margin: 0 auto;
  width: 200px;

  & .left {
    background: dodgerblue;
    padding: 5px;
    color: #fff;
  }

  & .right {
    background: green;
    color: #fff;
    padding: 5px;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  & .icon {
    padding: 5px;
    color: #fff;
    background: orange;
  }
}
<section>
  <div class="left">
    Left
  </div>
  <div class="right">
    Right Lots-Of-Text-Data
  </div>
  <div class="icon">
    Icon
  </div>
</section>


Solution

  • You need to include overflow: hidden to your truncated element.

    section {
      display: flex;
      border: 3px solid red;
      margin: 1em auto;
      width: 200px;
    }
    
    .wider {
      width: 400px;
    }
    
    section .left {
      background: dodgerblue;
      padding: 5px;
      color: #fff;
    }
    
    section .right {
      background: green;
      color: #fff;
      padding: 5px;
      flex: 1;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    
    section .icon {
      padding: 5px;
      color: #fff;
      background: orange;
    }
    <section>
      <div class="left">
        Left
      </div>
      <div class="right">
        Right Lots-Of-Text-Data
      </div>
      <div class="icon">
        Icon
      </div>
    </section>
    
    <section class="wider">
      <div class="left">
        Left
      </div>
      <div class="right">
        Right Lots-Of-Text-Data
      </div>
      <div class="icon">
        Icon
      </div>
    </section>