2013-04-23 94 views
1

我有两个<div/>以“列A”和“列B”方式排列。 B列是设定的宽度,我希望A列占据剩余的空间。有没有办法在CSS中实现这一点?或者也许是我正在做的更好的选择?根据同级宽度确定div的宽度

这是结构:

<div> 
    <div id='colA'>style is float right</div> 
    <div id='colB'>this has a set width of 50px</div> 
<div> 
+0

为什么不固定一个div的宽度,让另一个占用剩余宽度,你甚至不需要做任何事情 – inputError 2013-04-23 15:36:41

+0

可能的重复[如何保持两个并排,如果第二个具有长文本](http://stackoverflow.com/questions/5383299/how-to-keep-two-div-side-by-side- if-the-second-has-a-long-text) – 2013-04-23 15:44:42

回答

3

在它们中的一个使用float并添加余量为等于在该方向上浮动的宽度的其它..

<div> 
    <div id='colA'>this has a set width of 50px and is floated</div> 
    <div id='colB'>style has margin equal to floated width</div> 
</div> 

#colA { 
    width:50px; 
    float:left; 
    background-color:red; 
} 
#colB { 
    margnin-left:50px; 
    background-color:green; 
} 

演示在http://jsfiddle.net/C3caq/1/

+0

我想OP想要一个固定宽度的列在右边,并有左边的div占用剩余的空间。 – Antony 2013-04-23 15:50:18

+0

+1很高兴记得'老派'的方式。 – 2013-04-23 15:51:31

+0

@Antony,OP可以将float和margin方向更改为'right',如http://jsfiddle.net/C3caq/2/ – 2013-04-23 15:53:26

5

使用display: table-cell

#container{ 
    display: table; 
    width: 100%; 
} 

#colA { 
    display: table-cell; 
} 

#colB { 
    display: table-cell; 
    width: 50px; 
} 

请参阅DEMO

+0

toooo对我来说很快:)但是我建议你建议一个像施工集(table> tr> td)的整个表。参见:http:// jsfiddle。净/ sPm9M/2 /从我的另一个答案启发这里:http://stackoverflow.com/questions/15627332/layout-with-divs-instead-of-table/15638656#15638656 – 2013-04-23 15:38:07

+0

@MilchePatern是的,它会更好即使大多数现代浏览器在没有它的情况下也可以很好地使用'table-row'。 – Antony 2013-04-23 15:53:42