2012-06-04 62 views
0

我想創建簡單的HTML。我想創建3個div。html中心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; 
} 
+0

你能預先指定的寬度和'#top_right'和'#top_left'的高度或在這些動態調整基於內容? –

+0

我假設高度爲85px(請參閱'#top_left')。由於它被稱爲'top_ ...',它可能是某種標題。至於寬度,請參閱我的答案,左欄和右欄真正靈活。 – Paul

+0

#top_left和#top_right是動態的,取決於屏幕的大小。中心只有1024像素寬度... – senzacionale

回答

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> 
+0

thx但這是沒有圖像。當我使用圖像時,我有問題 – senzacionale

+0

將背景圖像寬度寫爲相關元素的最小寬度。例如。如果pikacom_01.gif寬度爲50px,請寫入.left {min-width:50px} – jumancy

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; 
} 

+0

謝謝。我會盡力讓你知道 – senzacionale

+0

我不知道你的背景圖片的性質。如果對齊很重要,則可能必須將它們分配給..._內容div。 – Paul

+0

嗯現在我有寬度問題:50%。我可以使用動態尺寸嗎?如果中心爲1024像素,屏幕爲1920像素,則左右兩側不是50% – senzacionale