响应式CSS方法

时间:2012-08-23 13:42:58

标签: css

下图是我想要得到的图解。第一个数字代表较长的宽度,第二个数字代表较短的宽度。 所有红色块都保持在左右位置,黄色块应该遵循容器的宽度。

1enter image description here http://i.stack.imgur.com/6bHTo.jpg

继承了我目前的做法

/* the one with black border :) */
.container{
    position: relative;
}
/* red blocks have auto heights depends on its content */
.red{
    position: absolute;
    top: 0;
    width: 100px;
}
.red-left{
    left:0;
}
.red-right{
    right:0;
}
/* yellow block follow the width of the container but should leave spaces for the left and right */
.yellow{
    margin: 0 110px;
}

我对这种方法几乎感到满意但是,我注意到当红色块高于容器时,容器不会自动跟随其内容的高度。我知道不可能自动调高容器的高度,因为孩子们处于绝对位置。 :)

4 个答案:

答案 0 :(得分:1)

您是否考虑过使用CSS3 Flex Box?它会是这样的:

HTML:

<div class="container">
   <div class="red red-left">red-left<br>red-left<br>red-left<br>red-left<br>red-left</div>
   <div class="yellow">yellow<br>yellow</div>
   <div class="red red-right">red-right</div>
</div>

和Css:

.container{
  display: -webkit-box;
  -webkit-box-orient: horizontal;

  display: -moz-box;
  -moz-box-orient: horizontal;

  display: box;
  box-orient: horizontal;        
}

.red{
    background-color:red;  
    width:100px; 
}

.yellow{     
    background-color:yellow;
    -webkit-box-flex: 1;
    -moz-box-flex: 1;
    box-flex: 1;
}

看看这个小提琴:

http://jsfiddle.net/lucaslazaro/sjYNy/

编辑:

要了解有关Flex Box的更多信息,我建议使用此快速教程:http://www.html5rocks.com/pt/tutorials/flexbox/quick/

答案 1 :(得分:0)

也许有帮助:

<强> HTML

<div class="container">
    <div class="red red-left">red-left<br>red-left<br>red-left</div>
    <div class="yellow">yellow<br>yellow</div>
    <div class="red red-right">red-right</div>
</div>

CSS

/* the one with black border :) */
.container{
    position: relative;
}
/* red blocks have auto heights depends on its content */
.red{
    position: absolute;
    top: 0;
    width: 100px;
    background:red;
    height:auto
}
.red-left{
    left:0;
}
.red-right{
    right:0;
}
/* yellow block follow the width of the container but should leave spaces for the left and right */
.yellow{
    margin: 0 110px;
    background:yellow
}

<强> DEMO

答案 2 :(得分:0)

My Own Demo to make it easier.

我们在这里可以看到内容与容器重叠。

答案 3 :(得分:0)

使用:

div {
    display: table;
    width: 100%;
    table-layout: fixed;
}

div > div {
    display: table-cell;
}

查看完整代码:

http://jsfiddle.net/BF6La/