2011-09-24 21 views
0

我想對齊在我不會放棄任何寬度父格一格一元中心becouse它會根據屏幕大小傳播,有總共3元的DIV:如何對齊一個元素始終在div中居中沒有給它的父div賦予寬度?

  1. 按鈕
  2. 標題
  3. 標誌

按鈕將永遠是左對齊和標誌將右對齊,每當屏幕尺寸會變化和航向始終一致中心這樣 enter image description here

我的代碼在這裏 http://jsfiddle.net/7AE7J/1/ 請讓我知道我要去哪裏錯了,我應該申請什麼css來獲取元素(標題)對齊中心始終。

HTML

<div id="header"> 
    <div id="buttons"> 
     <a href="#" class="button_back">link 1</a> 
     <a href="#" class="button_back">link 2</a> 
    </div> 
     <h1>Heading of the page</h1> 
    <div id="logo"> 
     <a href="#"> 
      <img src="http://lorempixum.com/60/60" width="178" height="31" alt="logo" /> 
     </a> 
    </div> 
</div> 

CSS

#header { 
    background:green; 
    height:44px; 
    width:100% } 

#buttons { 
    float: left; 
    margin-top: 7px; 
    } 

#buttons a { 
    display: block; 
    font-size: 13px; 
    font-weight: bold; 
    height: 30px; 
    text-decoration: none; 
    color:blue; 
    float:left} 

#buttons a.button_back { 
    margin-left: 8px; 
    padding-left:10px; 
    padding-top: 8px; 
    padding-right:15px } 

#header h1 { 
    color: #EEEEEE; 
    font-size: 21px; 
    padding-top: 9px ; 
    margin:0 auto} 

#logo { 
    float: right; 
    padding-top: 9px; 
    } 
+0

得到母體寬度:100%;如果你正在使用邊際自動技巧,這將工作。 – Kyle

+0

@凱爾 - 我試過了,但沒有任何區別 – Jamna

回答

6

您可以使用inline-block此:

#header { 
    text-align: center; 
} 

#header h1 { 
    display: inline-block; 
} 
-2

嘗試

.centered { 
    margin: 0 auto; 
} 
+0

這要求元素具有給定的寬度。否則,它佔用了容器的寬度(即100%) –

+0

我知道,我認爲元素具有給定的寬度。 –

0

這樣如何:

#header { 
    position: relative; 
    text-align: center; 
} 

#header h1 { 
    display: inline; 
} 

#header #buttons { 
    position: absolute; 
    left: 0; 
    top: 0; 
} 

#header #logo { 
    position: absolute; 
    right: 0; 
    top: 0; 
} 

display: inline實際上是一個位更跨瀏覽器比display: inline-block;

+0

嗨Niko, 我嘗試了你在這裏說的任何話,是的,現在我的標題元素是中心對齊,但它不能正常工作,請參閱這裏http://jsfiddle.net/jamna/LeXN9/4/ – Jamna

+0

我已經更新了兩個css和小提琴,請看這裏http://jsfiddle.net/LeXN9/5/ - #logo需要通過'top'屬性的y座標。 – Niko

相關問題