html中心div总是在中间,另外两个是动态的

时间:2012-06-04 07:37:43

标签: html

我想创建简单的HTML。我想创建3个div。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="generator" content="" />
    <meta name="keywords" content="" />
    <meta name="description" content="" />
    <link rel="stylesheet" type="text/css" href="style.css" media="screen">
    <title>My Site</title>
</head>
<body>
    <div id="top_left">
        &nbsp;
    </div>
    <div id="top_center">
        &nbsp;
    </div>
    <div id="top_right">
        &nbsp;
    </div>
</body>
</html>

中心div是固定大小,总是在中间。但第一和第三个div是动态的。如何做到这一点。

CSS

#top_left {
    background-image: url(images/pikacom_01.gif);
    background-repeat: repeat-x;    
    background-position: left;
    height: 85px;
}

#top_center {
    background-image: url(images/pikacom_02.gif);
    background-repeat: no-repeat;
    background-position: center;    
    width: 1024px;
    margin: 0 auto;
    height: 85px;
}

#top_right {
    background-image: url(images/pikacom_03.gif);
    background-repeat: repeat-x;
    background-position: right; 
}

2 个答案:

答案 0 :(得分:2)

<style type="text/css">
.left {float:left;}
.center {width:1024px;margin:0 auto;}
.right {float:right;}
</style>
<div class="right"></div>
<div class="left"></div>
<div class="center"></div>

答案 1 :(得分:1)

诀窍是左右列的宽度为50%,左或右浮动,左边或右边分别为负边距。负边距应为中心列宽的一半,因此在您的情况下为-512px。

然后在左右列中添加内容div,并为它们赋予相同值的正边距(512px)。

就是这样,请看我的demo。请注意html元素的更改顺序(中心位于最后)。此外,在演示中心div的宽度仅为300px,用于说明。

#top_left {
    background: #00f; // background-colors only added for illustration purposes
    background-image: url(images/pikacom_01.gif);
    background-repeat: repeat-x;    
    background-position: left;
    height: 85px;
    float: left;
    width: 50%;
    margin-left: -512px;
}
#top_left_content {
  margin-left: 512px;
}

#top_center {
    background: #f0f;
    background-image: url(images/pikacom_02.gif);
    background-repeat: no-repeat;
    background-position: center;    
    width: 1024px;
    margin: 0 auto;
    height: 85px;
}

#top_right {
    background: #ff0;
    background-image: url(images/pikacom_03.gif);
    background-repeat: repeat-x;
    background-position: right; 
    height: 85px;
    float: right;
    width: 50%;
    margin-right: -512px;
}
#top_right_content {
  margin-right: 512px;
}