开发者

CSS: resize div width according to parents width

开发者 https://www.devze.com 2023-01-30 17:39 出处:网络
Ok, I am basically building a fluid layout. My HTML is like this: <div id=\"container\"> <div class=\"box\" id=\"left\">Left</div>

Ok, I am basically building a fluid layout. My HTML is like this:

<div id="container">
    <div class="box" id="left">Left</div>
    <div class="box" id="center">This text is long and can get longer</div>
    <div class="box" id="right">Right</div>
    <div class="clear"></div>
</div>

Here is the css:

#container{
    width: 100%;
}
.box{
   开发者_Python百科 float: left;
}
#left, #right{
    width: 100px;
}
#center{
    width: auto; /* ? */
    overflow: hidden;
}
.clear{
    clear:both;
}

What I need to know is how do I get the #center to re-size when #container is re-sized without the elements moving underneath each other.


Try these corrections (just simple floating elements, no need to set absolute elems or paddings)

just added a new fiddle

<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="utf-8">
<title>fluid layout</title>
<style>
    /*class to set the width of the columns */
    .floatbox{
        width:100px;
    }

    #container{
        width: 100%;
        float:left;
    }
    #left{
        float:left;
    }
    #right{
        float:right;
    }
    #center{
        overflow: hidden;
    }
    .clear{
        clear:both;
    }
</style>
</head>
<body>
    <div id="container">
        <!-- floating column to the right, it must be placed BEFORE the left one -->
        <div class="floatbox" id="right">Right</div>
        <div class="floatbox" id="left">Left</div>

        <!-- central column, it takes automatically the remaining width, no need to declare further css rules -->
        <div id="center">This text is long and can get longer</div>

        <!-- footer, beneath everything, css is ok -->
        <div class="clear"></div>
    </div>
</body>
</html>


#container also must be floated (or with overflow: auto/hidden) to achieve it. I strongly suggest you use some of the more well known fluid solutions: http://www.noupe.com/css/9-timeless-3-column-layout-techniques.html


The easiest way to do this and completely avoid the float issues that arise would be to use padding on the container and absolute position the left/right elements in the padding area. (demo at http://www.jsfiddle.net/gaby/8gKWq/1)

Html

<div id="container">
    <div class="box" id="left">Left</div>
    <div class="box" id="right">Right</div>
    <div class="box" id="centre">This text is long and can get longer</div>
</div>

The order of the divs does not matter anymore..

Css

#container{
    padding:0 100px;
    position:relative;
}
.box{
   /*style the boxes here*/
}
#left, #right{
    width: 100px;
    position:absolute;
}
#left{left:0;top:0;}
#right{right:0;top:0;}

#center{
   /*anything specific to the center box should go here.*/
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号