将固定宽度的div背景拉伸到浏览器窗口的一侧?

时间:2014-08-28 06:19:56

标签: html css html5 css3

想象一下具有如下基本结构的页面。主要问题是如何让.left背景一直延伸到窗口的左侧,而.right则延伸到右侧?两者都需要保持固定宽度。

HTML:

<body>
    <div class="container">
        <header>blah</header>
        <article>doodle doo</article>
        <div class="left">Left stuff with blue background</div>
        <div class="right">Right stuff with red background</div>
        <div class="clear"></div>
    </div>
        <footer>deedle dee</footer>
</body>

CSS:

.container{
    width:400px;
    margin:0 auto;
}
header{
    background-color:grey;
}
.left{
    width:200px;
    float:left;
    background-color:blue;
}
.right{
    width:200px;
    float:right;
    background-color:red;
 }
.clear{
    clear:both;
}
footer{
    background-color:#DDD;
    text-align:center;
}

Fiddle here

基本思想与this page相同,但你可能会注意到页面向右滚动 - 切断实际上并不起作用。

2 个答案:

答案 0 :(得分:1)

我用display: table和伪元素实现了这一点。

此解决方案的基础知识:

  • 包装器.content被设为display: table并被赋予position: fixed以允许其“单元格”具有固定宽度。如果需要,请使用border-spacing: unit size;

  • 提供间距
  • .left.right已获得display: table-cell

  • .content:before.content:after提供伪列(也包含display: table-cell)以隔离背景。

Have an example!

HTML

<header></header>
<article></article>
<div class="content">
  <div class="column left"></div>
  <div class="column right"></div>
</div>
<footer></footer>

CSS

* {
  margin:0;
  padding:0
}

html,body {
  height:100%
}

.content {
  display:table;
  table-layout:fixed;
  height:100%;
  width:100%
}

header {
  background-color:grey;
  height:20px;
  width:500px;
  margin:0 auto
}

article {
  height:20px;
  width:500px;
  margin:0 auto
}

.column {
  display:table-cell;
  width:200px;
  vertical-align: top
}

.left {
  height:100%;
  background:blue
}

.content:before,.content:after {
  display:table-cell;
  content:'';
  background:blue;
  height:100%;
  vertical-align: top;
  padding-left:10%
}

.content:after {
  background:red;
  padding-right:10%
}

.right {
  background-color:red
}

footer {
  background-color:#DDD;
  text-align:center;
  height:50px
}

答案 1 :(得分:-1)

1)将您的leftright元素放入另一个容器中:

<div class="container">
    <header>blah</header>
    <article>doodle doo</article>
</div>

<div class="container2">
    <div class="left">
        <div class="text">Left stuff with blue background</div>
        <div class="clear"></div>
    </div>
    <div class="right">
        <div class="text">Right stuff with red background</div>
        <div class="clear"></div>
    </div>
</div>

<footer>deedle dee</footer>

2)container2宽度为100%,让leftright50%

.left {
    width:50%;
    float:left;
    background-color:blue;
}

.right {
    width:50%;
    float:right;
    background-color:red;
}

3)两列上的text元素应为200px

.text {
    width: 200px;
}

.left .text {
    float: right;
}

.right .text {
    float: left;
}

Working jsFiddle Demo