CSS:根据父元素的宽度调整div宽度

3

好的,我基本上正在构建一个流体布局。 我的HTML代码如下:

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

这里是CSS:
#container{
    width: 100%;
}
.box{
    float: left;
}
#left, #right{
    width: 100px;
}
#center{
    width: auto; /* ? */
    overflow: hidden;
}
.clear{
    clear:both;
}

我需要知道的是如何在不让元素相互移动的情况下,当重新调整#container大小时,使#center也跟着重新调整大小。

只是一个简单的更正:<div class="box" id="centre">这个文本很长,可能会更长</div>,id应该改为"center" ;) - stecb
干杯,我简直不敢相信我做到了。 - Franky Chanyau
3个回答

2

尝试这些改正(只是简单的浮动元素,不需要设置绝对元素或填充)

刚刚添加了一个新的范例

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

1

最简单的方法是使用容器的内边距(padding)来避免出现浮动(float)问题,然后将左/右元素绝对定位于内边距区域。(示例请参考 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>
div的顺序不再重要了。
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.*/
}

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接