2010-12-14 113 views
3

好的,我基本上构建了一个流体布局。 我的HTML是这样的:CSS:根据父母的宽度调整div宽度

<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重新大小元素在彼此之下移动。

+0

只是一个简单的修正:

This text is long and can get longer
id为 “中心”) – stecb 2010-12-14 13:45:40

+0

欢呼声,我不敢相信我做到了 – 2010-12-14 13:57:59

+0

不客气,没有probs; ) – stecb 2010-12-14 14:02:36

回答

2

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

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

要做到这一点,完全可以避免出现的将是在容器上 使用填充和绝对位置的左/右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.*/ 
}