Search code examples
htmlcsshorizontal-scrolling

Horizontally scrollable div inside full width div


enter image description here I have a division which horizontally fits the screen inside which I have 5 divisons, I want 4 divisions to appear on screen and 1 division to appear when I scroll the division horizontally. And I want the scrollbar to appear inside the div only and not on the browser window.

Below is my non working code which puts the h1 tag in the left, I want it on the top-left then under it all 5 divs

.outer {
  overflow-x: scroll;
  width: 100%;
}

.inner {
  width: 25%;
  float: left;
}
<div class="outer">
  <h1>Header Title</h1>
  <div class="inner">
  </div>
  <div class="inner">
  </div>
  <div class="inner">
  </div>
  <div class="inner">
  </div>
  <div class="inner">
  </div>
</div>


Solution

  • You can do it with Flexbox:

    .outer {
      display: flex; /* displays flex-items (children) inline */
      overflow-x: auto;
    }
    
    .inner {
      flex: 0 0 25%; /* doesn't grow nor shrink, initial width set to 25% of the parent's */
      height: 1em; /* just for demo */
    }
    <div class="outer">
      <div class="inner" style="background: red"></div>
      <div class="inner" style="background: green"></div>
      <div class="inner" style="background: blue"></div>
      <div class="inner" style="background: yellow"></div>
      <div class="inner" style="background: orange"></div>
    </div>

    Solution with the h1 element:

    .outer {
      display: flex;
      flex-direction: column;
      overflow-x: auto;
    }
    
    .middle {
      display: flex;
      flex: 1;
    }
    
    .inner {
      flex: 0 0 25%;
      height: 1em;
    }
    <div class="outer">
      <h1>Header Title</h1>
      <div class="middle">
        <div class="inner" style="background:red"></div>
        <div class="inner" style="background:green"></div>
        <div class="inner" style="background:blue"></div>
        <div class="inner" style="background:yellow"></div>
        <div class="inner" style="background:orange"></div>
      </div>
    </div>