htmlcssresizewidth

How to keep elements on same line with overflow


I am trying to make a page with some divs aligning horizontally and I want the width to resize based on content so I will get a horizontal scroll if the content is bigger than screen size. I have this:

    <div>
    <div style="width: 300px; height: 300px; background-color: black; margin-left: 10px; float: left;"></div>
    <div style="width: 300px; height: 300px; background-color: black; margin-left: 10px; float: left;"></div>
    <div style="width: 300px; height: 300px; background-color: black; margin-left: 10px; float: left;"></div>
    <div style="width: 300px; height: 300px; background-color: black; margin-left: 10px; float: left;"></div>
    <div style="width: 300px; height: 300px; background-color: black; margin-left: 10px; float: left;"></div>
</div>

the child divs are aligning side by side but when the screen size is reached it breaks into a new line. Any ideas ?


Solution

  • I would use white-space: nowrap along with display: inline-block. Live demo (click).

    By the way, try to use CSS instead of inline styles in your HTML. Inline styles should be avoided unless absolutely necessary.

    .row {
      white-space: nowrap;
    }
    
    .row>div {
      width: 300px;
      display: inline-block;
    }
    <div class="row">
      <div>1</div>
      <div>2</div>
      <div>3</div>
      <div>4</div>
    </div>