Home > Software design >  Overflow auto doesn't work because children is making parent bigger
Overflow auto doesn't work because children is making parent bigger

Time:05-02

My goal is to code a simple design with 2 columns - first of 250px width and second of the rest of free space. Inside the second column may be a huge element that must take 100% of parent width and be scrollable horizontally if is bigger than parent.

This is my CSS:

.layout {
  display: flex;
  padding: 20px;
}

.sidebar {
  width: 250px;
  background-color: red;
}

.content {
  flex-grow: 1;
  background-color: lightgreen;
}

.largeBox {
  overflow-x: auto;
  max-width: 100%;
}

.large {
  width: 900px;
  height: 50px;
  background: rgb(34, 193, 195);
}

It doesn't work because it makes first column to shrink to it's content instead of taking 250px. When i make it min-width then the entire page gets scrollbar. How to implement this design? Link to the code: https://codesandbox.io/s/affectionate-meadow-c9txz1

CodePudding user response:

You can try to replace width with min-width

.sidebar {
  min-width: 250px;
  background-color: red;
}

CodePudding user response:

Would you consider shifting to CSS Grid? Your life will get exponentially easier when you start using 'fr' units, i.e. remaining space.

.layout {
  display: grid;
  grid-template-columns: 250px 1fr;
  overflow: scroll;
}

.sidebar {
}

.content {
}

Then, to hide the scrollbar:

scrollbar-width: none; // firefox
&::-webkit-scrollbar { display: none; } // Chrome, Safari and Opera
-ms-overflow-style: none; //IE and Edge

You don't need to tell the kids what to span, the parent grid will instruct them in the order you declare them. i.e. the sidebar will be 250px, the content will take up the remaining space (1fr).

CodePudding user response:

body {
  margin: 0;
}

.layout {
  display: flex;
  padding: 20px;
}

.sidebar {
  flex-shrink: 0;
  width: 250px;
  background-color: red;
}

.content {
  flex-grow: 1;
  background-color: lightgreen;
  max-width: 100%;
}

.largeBox {
  overflow-x: auto;
  max-width: 100%;
}

.large {
  width: 900px;
  height: 50px;
  background: rgb(34, 193, 195);
  background: linear-gradient(
    106deg,
    rgba(34, 193, 195, 1) 0%,
    rgba(253, 187, 45, 1) 35%,
    rgba(45, 253, 149, 1) 100%
  );
}
<body>
<div >
      <div >
        <p>sidebar</p>
      </div>
      <div >
        <p>this is epic</p>

        <div >
          <div ></div>
        </div>

        <p>Thank you!</p>
      </div>
        
  </div>  
</body>    

You need use flex-shrink: 0 within .sidebar.

  • Related