棘手的CSS定位问题

时间:2010-08-19 15:21:09

标签: css

我的body有一个平铺背景(附图中的蓝色)

我需要水平居中一些固定的宽度和高度内容(绿色),距离页面顶部固定距离。

然后我需要将居中内容的背景图像继续到页面的左右两端,无论浏览器是多宽(紫色)

原因是绿色内容中有一个“洞”,可以显示body背景。如果这不是一个要求id使紫色成为包裹内容的100%宽度div,并简单地给它平铺背景图像。

alt text

到目前为止,我已经成功了:

<div id="Left"></div>
<div id="Right"></div>
<div id="Content"></div>


#Left
{
    width: 50%;
    margin-right: 480px;
    position: absolute;
    top: 50px;
    right: 50%;
    height: 525px;
    background: transparent url(/images/purple.png) repeat-x scroll center top;
}
#Right
{
    width: 50%;
    margin-left: 480px;
    position: absolute;
    top: 50px;
    left: 50%;
    height: 525px;
    background: transparent url(/images/purple.png) repeat-x scroll center top;
}

#Content
{
    position: absolute;
    top: 50px;
    left: 50%;
    margin-left: -480px;
    width: 960px;
    height: 525px;
    background: transparent url(/images/green.png) no-repeat scroll center top;
}

哪个 工作,除了页面有一个水平滚动条,右手紫色延伸到某种程度。我怎么能克服这个?

我不能通过简单地复制背景来欺骗洞,我想避免在身体上放置overflow-x: hidden

编辑:我还需要一个可变高度页面,因为给定的525px height可能会更大,因此页面需要进行v滚动。

这需要在IE7 +,FF,Safari

中运行

由于

3 个答案:

答案 0 :(得分:1)

我认为这应该可以解决问题:

<html>

<head>
<style type="text/css">

body
{
    overflow-x: hidden;
    width: 100%;
    margin: 0;
    padding: 0;
}

#Left
{
    width: 50%;
    margin-right: 480px;
    position: absolute;
    top: 50px;
    right: 50%;
    height: 5525px;
    border: solid 2px purple;
}
#Right
{
    width: 50%;
    margin-left: 480px;
    position: absolute;
    top: 50px;
    left: 50%;
    height: 5525px;
    border: solid 2px purple;
}

#Content
{
    position: absolute;
    top: 50px;
    left: 50%;
    margin-left: -480px;
    width: 960px;
    height: 5525px;
    border: solid 2px green;
}

</style>
</head>

<body>

<div id="Left"></div>
<div id="Right"></div>
<div id="Content"></div>

</body>
</html>

我在body标签中添加了样式(以防止水平滚动条),我在Content div上使用了“auto”边距(不确定是否有必要,但我就是这样做的)。

如果我遗漏了一些东西,请告诉我。

编辑:

我把绝对定位放回内容div。 GD你是Internet Explorer ......

答案 1 :(得分:0)

通常我可以通过设置来解决这个问题:

#content{
  margin-right:auto;
  margin-left:auto;
}

你可以取消左和右(当然除非你想保留它们)。

然后获得洞只是使内容的背景成为png图像并使孔透明。那时它在div上显得透明。

答案 2 :(得分:0)

<!doctype html>
<style>
body {
    background: blue;
    margin: 0;
}
#wrapper {
    height: 300px;
    margin-left: 50%;
    position: relative;
    top: 100px;
}
#left {
    background: magenta;
    height: 300px;
    margin-right: 300px;
    position: absolute;
    right: 100%;
    width: 100%;
}
#center {
    border: 100px solid lime;
    float: left;
    height: 100px;
    margin-left: -300px;
    width: 400px;
}
#right {
    background: magenta;
    height: 300px;
    overflow: hidden;
}
</style>

<div id="wrapper">
    <div id="left"></div>
    <div id="center"></div>
    <div id="right"></div>
</div>
  • 我在左侧使用绝对定位,因为无论如何你从来没有得到滚动条。
  • 我浮动了中心div,所以我可以使用the "secret benefit" of overflow填写屏幕右侧而不创建滚动条。
  • 我使用边框到中心div来显示身体的蓝色背景确实“透视”,但你当然可以使用背景图像。

(我在IE3和IE7模式下在Firefox 3.6和IE8中进行了测试。)