Yellow and Red Yellow and Red - 1 month ago 6
CSS Question

padding on child element moves parent element - CSS

I am building a gallery that is full screen and the



#cover {
position: absolute;
width: 500px;
height: 500px;
background: rgba(44, 69, 128, 0.65);
z-index: 10;
}
.divHolder {
background: #fff;
color: #2c4580;
position: relative;
box-shadow: 2px 2px 2px #333;
padding: 10px;
margin: 20px 20px;
overflow: auto;
height: 100%;
}
.divHolder div:hover {
border: 10px solid #000;
}
.divHolder div {
width: 100px;
height: 100px;
background: black;
padding: 10px;
display: inline-block;
cursor: pointer;
border: 10px solid white;
}

<div id="cover">
<div class="divHolder">
<div>image</div>
...
<div>image</div>
</div>
</div>





OUTPUT:
Output

How to fit in the child div "divHolder" holder inside the "holder". I always do not understand the way the padding and margins work with child divs.

for reference, I have added the code jsfiddle

Answer

You can just use calc() to calculate the proper height for .divHolder. Because of your margin, the .divHolder exceeds the parent container because you set it to height: 100%;. Reduce the 100% by your top and bottom margin and it should fit:

height: calc(100% - 40px);

#cover {
  position: absolute;
  width: 500px;
  height: 500px;
  background: rgba(44, 69, 128, 0.65);
  z-index: 10;
}
.divHolder {
  background: #fff;
  color: #2c4580;
  position: relative;
  box-shadow: 2px 2px 2px #333;
  padding: 10px;
  margin: 20px 20px;
  overflow: auto;
  height: calc(100% - 40px);
  box-sizing: border-box;
}
.divHolder div:hover {
  border: 10px solid #000;
}
.divHolder div {
  width: 100px;
  height: 100px;
  background: black;
  padding: 10px;
  display: inline-block;
  cursor: pointer;
  border: 10px solid white;
}
<div id="cover">
  <div class="divHolder">
    <div>image</div>
    <div>image</div>
    <div>image</div>
    <div>image</div>
    <div>image</div>
    <div>image</div>
    <div>image</div>
    <div>image</div>
    <div>image</div>
    <div>image</div>
    <div>image</div>
    <div>image</div>
  </div>
</div>

Comments