Mattia Del Franco
Mattia Del Franco

Reputation: 385

Take height of parent and assign to child with jQuery

I have this CSS and HTML structure:

.body_wrapper {
  height: 100%;
  }

.forumcontents {
  width: calc(100% - 290px) !important;
  float: left;
  }

.sidebar_container {
  width: 270px;
  float: right;
  height: 100%;
  }

.clearfix {
   zoom: 1;
   clear: both;
  }
<div class="body_wrapper clearfix">
    <div class="forumcontents"></div>
    <div class="sidebar_container"></div>
</div>

Unfortunately, i need to float .sidebar_container, but with the float, this div doesn't take the 100% of the height of .body_wrapper and I for some reasons can't use the absolute positioning.

I tried with a display: table-cell to .sidebar_container but doesn't work, so i thought that the only solution is to take the .body_wrapper height after page loading ad assign it to the .sidebar_container.

How I can do this with jQuery?

Upvotes: 0

Views: 44

Answers (2)

Sully
Sully

Reputation: 1353

Here is the jquery

$(function () {
    $(".sidebar_container").height($(".body_wrapper").height());
});

Here is a fiddle showing it in action (I added borders to show boundaries): http://jsfiddle.net/48uxr49p/

However, in the jsfiddle, using height:100% on sidebar works fine (I commented it out to show that the jquery works). You may want to dig around to see if there is another element/CSS preventing height:100% from working.

Here is the jsfiddle demonstrating that height:100% works: http://jsfiddle.net/w3dmx7qm/

Upvotes: 1

Paulie_D
Paulie_D

Reputation: 114991

You can do that with flexbox.

* {
  margin: 0;
  padding: 0;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
html,
body {
  height: 100%;
}
.body_wrapper {
  height: 100%;
  background: #f00;
  display: flex;
}
.forumcontents {
  flex: 1;
  background: lightgreen;
}
.sidebar_container {
  flex: 0 0 270px;
  background: lightblue;
}
<div class="body_wrapper">
  <div class="forumcontents"></div>
  <div class="sidebar_container"></div>
</div>

Upvotes: 0

Related Questions