2012-10-28 41 views
1

在我的頁面上,我在頭部區域中有兩個元素。我希望第一個元素位於標題區域的中間位置,第二個元素將一直推到標題區域的右側。我實現了使用此代碼預期的效果:內聯元素改進的水平對齊

<div id="header-area" style="text-align:center;width:100%;"> 
    <div id="partition1" style="display:inline-block;width:33%;"></div> 
    <div id="partition2" style="display:inline-block;width:33%;"> 
    <div id="element1" style="display:inline;width:400px;height:100px;"> 
     <h3 style="display:inline;width:400px;">Main title Goes Here</h3><br/><br/> 
     <p style="display:inline;width:400px;">Subtitle goes here</p> 
    </div> 
    </div> 
    <div id="partition3" style="display:inline-block;width:33%;text-align:right;"> 
    <div id="Element2" style="display:inline;width:150px;vertical-align:middle;"> 
     <button onclick="history.back();" style="height:45px;width:100px;"> 
     Back</button> 
    </div> 
    </div> 
</div> 

你會發現我劃分的header-area爲三個空間,並對齊它們各自的分區中的element1 & element2。如何在不劃分header-area的情況下實現相同的佈局?

回答

3

有幾種方法可以做到這一點。這裏有兩個:

選項#1:浮動

的HTML:

<div id="header"> 
    <div class="right">Element on right end</div> 
    <div class="center">Center-Aligned Element</div> 
</div> 

的CSS:

#header { 
    text-align: center; 
} 

#header div.center { 
    margin: 0 auto; 
    text-align: center; 
    width: 30%; 
} 

#header div.right { 
    float: right; 
    text-align: right; 
} 

選項#2:位置絕對

HTML:

<div id="header"> 
    <div>Center-Aligned Element</div> 
    <div class="right">Element on right end</div> 
</div> 

的CSS:

#header { 
    text-align: center; 
} 

#header div { 
    text-align: center; 
    width: 30%; 
    margin: 0 auto; 
} 

#header div.right { 
    position: absolute; 
    top: 0; 
    right: 0; 
    text-align: right; 
} 

示例使用您的元素:

的HTML:

<div id="header"> 
    <h3>Main Title Goes Here</h3> 
    <p>Subtitle Goes Here</h3> 
    <button>Element on right end</button> 
</div> 

的CSS:

#header { 
    text-align: center; 
} 

#header h3, 
#header p { 
    margin: 0 auto; 
    text-align: center; 
    width: 30%; 
} 

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