Biker John
Biker John

Reputation: 2711

Prevent element from overflowing container

I have the following structure, where the number of names (.name) in .list is dynamic. What i would like to achieve is when content (depending on n of .names) is longer than .parent's fixed height, both .children fit inside the .parent (inherit height). Lack of space would be solved with .list getting a scrollbar (overflow:auto).

Height inheritance works well with single child, but I am having huge problems when there are two or more.

enter image description here

JSFIDDLE HERE

HTML

<div id="grandparent">
  <div id="parent">
    <div id="list" class="children">

      <div class="name">john</div>
      <div class="name">mike</div>
      <div class="name">jack</div>
      <div class="name">terry</div>

    </div>

    <div id="footer" class="children">

      <div>footer</div>

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

CSS

body, html {

  margin: 0;
  width: 100%;
  height: 100%;

}

div {

  box-sizing: border-box;

}

#grandparent {

  background-color:yellow;
  display:flex;
  align-items:center;
  width:100%;
  height: 100%;
  flex: 1;

}

.children, .children div {

  padding: 5px;

}

.children {

  max-height: inherit;

}

.children div {

  width: 100%;
  max-height: inherit;

}

#list {

  overflow: auto;
  padding-bottom:0;

}

#footer {

  padding-top:0;

}

.name {

  background-color: green;

}

#footer div {

  background-color: pink;

}

#parent {

  background-color: blue;
  margin: 0 auto;
  max-height: 100px;

}

P.S. sorry for the code mess, i was just testing out different options.

Upvotes: 1

Views: 3297

Answers (1)

Michael Benjamin
Michael Benjamin

Reputation: 370993

Add this to your code:

#parent {
  display: flex;
  flex-direction: column;
}

body,
html {
  margin: 0;
  width: 100%;
  height: 100%;
}

div {
  box-sizing: border-box;
}

#grandparent {
  background-color: yellow;
  display: flex;
  align-items: center;
  width: 100%;
  height: 100%;
  flex: 1;
}

.children,
.children div {
  padding: 5px;
}

.children {
  max-height: inherit;
}

.children div {
  width: 100%;
  max-height: inherit;
}

#list {
  overflow: auto;
  padding-bottom: 0;
}

#footer {
  padding-top: 0;
}

.name {
  background-color: green;
}

#footer div {
  background-color: pink;
}

#parent {
  background-color: blue;
  margin: 0 auto;
  max-height: 100px;
  
  /* new */
  display: flex;
  flex-direction: column;
}
<div id="grandparent">
  <div id="parent">
    <div id="list" class="children">
      <div class="name">john</div>
      <div class="name">mike</div>
      <div class="name">jack</div>
      <div class="name">terry</div>
    </div>
    <div id="footer" class="children">
      <div>footer</div>
    </div>
  </div>
</div>

jsFiddle demo

Because flex items are set to flex-shrink: 1 by default, they will reduce their size in order to not overflow the container.

Upvotes: 2

Related Questions