简体   繁体   中英

Do I have to set the height of the container?

I have this code:

#container {
    position:relative;
    width:760px;    

    margin-left: auto;
    margin-right: auto;
    margin-top: 10px;

    border: 1px solid #cdcdcd;  
}

#sidebar {
    float:left;
    width: 200px;
    background:red;
}

#wrapper {
    float:left;
    width:460px;
background:blue;

}

and this HTML CODE:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

    <head>
        <title>Example.com</title>
        <link rel="stylesheet" type="text/css" href="style.css"/>
    </head>
    <body>
        <div id="container">
            <div id="sidebar">
                        LEFT
            </div>

            <div id="wrapper">
                RIGHT
            </div>          
        </div>  
    </body>
</html>

I see that the container has no height.... do I Must set it? I would like to explain the height depending on the height of the inner DIVs, How could i do it?

You do not have to set the height, just add:

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

directly below any divs that you float.


In your case, you could do this:

Just add this to your CSS file.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

    <head>
        <title>Example.com</title>
        <link rel="stylesheet" type="text/css" href="style.css"/>
    </head>
    <body>
        <div id="container">
            <div id="sidebar">
                        LEFT
            </div>

            <div id="wrapper">
                RIGHT
            </div>    
            <div class="clear"></div>      
        </div>  
    </body>
</html>

And update your HTML file to match

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Example.com</title> <link rel="stylesheet" type="text/css" href="style.css"/> </head> <body> <div id="container"> <div id="sidebar"> LEFT </div> <div id="wrapper"> RIGHT </div> <div class="clear"></div> </div> </body> </html> 

That happens because you used float:left . One solution is to add a clear:both div as follow:

CSS:

.clear {
    clear: both;
}

HTML:

<div id="container">
    <div id="sidebar">LEFT</div>
    <div id="wrapper">RIGHT</div>
    <div class="clear"></div>
</div>  

Give the container the additional CSS

overflow: hidden;

This will break the float with no extra markup
(Will not work with box-shadow inside)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM