How can I make the height of a div section to automatically adapt to the height of its content?
Tags: html,css,layout
Problem :
I have a div
container with id=middle
that is centered in the page by this code:
header, #middle, footer {
margin-left: auto;
margin-right: auto;
}
Inside the div
named middle
there are the nav
and the main
section. The div
is acting like a container for the nav
and the main
, so it should be easier to align the nav
to the left and main
to the right while keeping them centered.
I tried to do such alignment by the following code:
#middle {
width: 849px;
height: 600px; /*I wanto to set this to auto or get rid of it*/
}
nav {
width: 200px;
float: left;
}
main {
width: 649px;
float: right;
}
It works, but I have to specify the height of #middle
, it doesn't automatically adapt to the height of its content, messing up all the rest of the layout. In my site, the height of main and nav varies from page to page.
How can I fix this? I don't want to specify a fixed height for #middle
, instead I would like that #middle
varies its height depending on the maximum height between main
and nav
.
I don't know if it is useful but the CSS code ends with:
footer {
width: 849px;
height: 50px;
}
And this is the HTML code of my page:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<header>
...
</header>
<div id="middle">
<nav>
...
</nav>
<main>
...
</main>
</div>
<footer>
...
</footer>
</body>
</html>
N.B. nav
and main
are the semantic html5 tags, similar to div
Solution :
Add a <div>
with clear: both;
after </main>
. Then You can remove height of #middle