CSS dynamic height based on child elements

10,614

If you float content inside container div (if it doesn't have any other non-floated content), it will remain 0, but to fix this, you can add a

<div style="clear: both"></div>

before your parent elements ends (so right before of your parent). I'ts not the most elegant solution, but works like charm, and there are no real alternatives that i know of.

Share:
10,614
TheLegend
Author by

TheLegend

#SOreadytohelp. I am a Software Developer here in Cape Town, South Africa. I mostly work on web apps, mostly in Ruby and Rails. I started back in Nov 2011. I work for a company called Peach Payments as their head of engineering. Above all else, I love simple easy to read code. I am a student of the software development process. I find the glue that holds domains together as interesting as the domains themselves.

Updated on June 04, 2022

Comments

  • TheLegend
    TheLegend about 2 years

    cool so i have been exploring CSS with HTML fo about a month now and the one thing i am still struggling with is how to get a element to adjust its height based on the height on the children. so for example i have a news button that will take me to a page that has links to an archive of articles printed at different times, the articles vary in length, but the content element that holds it all, always allows the articles to overflow and then i have to use scroll, is there away to set the height to adjust to the children elemets inside.

    i have tried:

    height: 100%;
    

    if i inspect element the metrics say its at 647px. and then it stays there

    height: auto;
    

    sets the height at 200px, and everything is overflowed.

    this is a section of html nesting..

     <div id="news_head">
     </div>
     <div id="news_content">
       <div id="news_scroll">
       </div>
       <div id="news_main_page">
       </div>
       <div id="side_archive">
       </div>
     </div>
     <div id="disquss_section">
     </div>
    

    the css for this is:

    #news_head {
      border: 1px solid red;
      height: 200px;
      width: 100%;
    }
    
    #news_content {
      border: 1px solid red;
      height: 100%;
      width: 1200px;
      margin: 5px auto;
    }
    
    #news_scroll {
      border: 1px solid green;
      width: 1198px;
      height: 200px;
    }
    
    #news_main_page {
      border: 1px solid blue;
      width: 988px;
      height: 430px;
      float: left;
    }
    
    #side_archive {
      border: 1px solid yellow;
      width: 200px;
      height: 430px;
      float: right; 
    }
    

    i am using the bordering just to see a visual as to what is going on. i have read some things but i am not exactly sure how to implement it here, http://css-tricks.com/snippets/css/center-div-with-dynamic-height/. any help, i am using JavaScript and jQuery as well, so any suggestions are welcome.