如何使div部分的高度自动适应其内容的高度?

时间:2022-01-03 20:12:03

I have a div container with id=middle that is centered in the page by this code:

我有一个id = middle的div容器,它通过以下代码在页面中居中:

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.

在名为middle的div里面有导航和主要部分。 div就像nav和main的容器一样,因此将导航器向左和向右对齐应该更容易,同时保持它们居中。

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.

它有效,但我必须指定#middle的高度,它不会自动适应其内容的高度,弄乱所有其余的布局。在我的网站中,主页和导航的高度因页面而异。

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.

我怎样才能解决这个问题?我不想为#middle指定一个固定的高度,而是希望#middle根据main和nav之间的最大高度来改变它的高度。

I don't know if it is useful but the CSS code ends with:

我不知道它是否有用但CSS代码的结尾是:

footer {
    width: 849px;
    height: 50px;
}

And this is the HTML code of my page:

这是我的页面的HTML代码:

<!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

注: nav和main是语义html5标签,类似于div

1 个解决方案

#1


1  

Add a <div> with clear: both; after </main>. Then You can remove height of #middle

添加一个带有clear的

:both;在 之后。然后你可以删除#middle的高度

#1


1  

Add a <div> with clear: both; after </main>. Then You can remove height of #middle

添加一个带有clear的

:both;在 之后。然后你可以删除#middle的高度