0

In the code below, the parent div holds 4 divs. Next, using CSS, I'm hiding a child div (.layer_active class). How can I dynamically change the dimensions of the parent div? Ideally, I want to dynamically modify the height of the parent based on the number of visible divs inside it.

.map-overlay {
  background-color: #6baed6;
  border-radius: 3px;
  bottom: 30px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  font: 12px/20px "sans-serif", Arial, Helvetica;
  padding: 10px;
  position: absolute;
  right: 10px;
  z-index: 1;
}

.legend_item div span {
  /* border-radius: 50%; */
  display: inline-block;
  min-height: 10px;
  margin-right: 5px;
  width: 10px;
  /* margin-bottom: .0px */
}

.legend_item.layer_active{
  visibility: hidden;
}
<div class="map-overlay" id="legend">
  <div class="legend_item">
    <h4>Dummy text</h4>
    <div><span style="background-color: #F7FBFF"></span>Dummy</div>
  </div>
  
  <div class="legend_item">
    <h4>Dummy text</h4>
    <div><span style="background-color: #F7FBFF"></span>Dummy</div>
  </div>
  
  <div class="legend_item">
    <h4>Dummy text</h4>
    <div><span style="background-color: #F7FBFF"></span>Dummy</div>
  </div>
  
  <div class="legend_item layer_active">
    <h4>Dummy text</h4>
    <div><span style="background-color: #F7FBFF"></span>Dummy</div>
  </div>
</div>
PPR
  • 395
  • 1
  • 5
  • 17

1 Answers1

1

You're using the visibility property instead of display. The difference between the two properties is explained in this answer.

To summarize, visibility: hidden keeps the element size intact and reserves space for it as if the element is still on the page. On the other hand, display: none effectively removes the element from the page, as if it was never there.

.map-overlay {
  background-color: #6baed6;
  border-radius: 3px;
  bottom: 30px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  font: 12px/20px "sans-serif", Arial, Helvetica;
  padding: 10px;
  position: absolute;
  right: 10px;
  z-index: 1;
}

.legend_item div span {
  /* border-radius: 50%; */
  display: inline-block;
  min-height: 10px;
  margin-right: 5px;
  width: 10px;
  /* margin-bottom: .0px */
}

.legend_item.layer_active {
  display: none; /* Fix */
}
<div class="map-overlay" id="legend">
  <div class="legend_item">
    <h4>Dummy text</h4>
    <div><span style="background-color: #F7FBFF"></span>Dummy</div>
  </div>

  <div class="legend_item">
    <h4>Dummy text</h4>
    <div><span style="background-color: #F7FBFF"></span>Dummy</div>
  </div>

  <div class="legend_item">
    <h4>Dummy text</h4>
    <div><span style="background-color: #F7FBFF"></span>Dummy</div>
  </div>

  <div class="legend_item layer_active">
    <h4>Dummy text</h4>
    <div><span style="background-color: #F7FBFF"></span>Dummy</div>
  </div>
</div>
thordarson
  • 5,943
  • 2
  • 17
  • 36