2013-03-01 106 views
8

我的代碼是這樣的。如何向右對齊div內的固定位置div

<div class="outer"> 
    <div class="inner">some text here 
    </div> 
</div> 

CSS:

.outer { 
    max-width:1024px; 
    background-color:red; 
    margin:0 auto; 
} 
.inner { 
    width:50px; 
    border:1px solid white; 
    position:fixed; 
} 

它位於左默認內格需有w.r.t外格,而不是頁面被定位。

如果我提到它是正確的:0px;它使它從瀏覽器中執行0px而不是外部div的右側。

注意:我的外部div不是固定寬度。它根據屏幕分辨率進行調整。它的響應式網站設計。

+0

謝謝,我必須添加最大寬度與%寬度,但它使得完美的解決方案。 – 2013-03-01 10:38:22

回答

9

你可以使用一個div容器:

<div class="outer"> 
    <div class="floatcontainer"> 
     <div class="inner">some text here</div> 
    </div> 
</div> 

然後用它來處理float,和讓其子女position: fixed

.outer { 
    width:50%; 
    height:600px; 
    background-color:red; 
    margin:0 auto; 
    position: relative; 
} 
.floatcontainer { 
    float: right; 
} 
.inner { 
    border:1px solid white; 
    position:fixed; 
} 
.floatcontainer, .inner{ 
    width: 50px; 
} 
7

你爲什麼不使用position:absolute

position:fixed總是相對於瀏覽器

.outer { 
    width:200px; 
    height:600px; 
    background-color:red; 
    margin:0 auto; 
    position:relative 
} 
.inner { 
    width:50px; 
    border:1px solid white; 
    position:absolute; right:0 
} 

DEMO


如果是強制使用position:fixed那麼你可以指定margin-left值,因爲你正在使用固定的兩個div。

.inner { 
    width:50px; 
    border:1px solid white; 
    position:fixed; margin-left:150px 
} 

DEMO 2

+0

你的第二個解決方案似乎正在工作,但與我的外部div的問題不是固定的寬度。它根據屏幕寬度自行調整。所以我不能在裏面聲明寬度。我已經在我的查詢中更新了 – 2013-03-01 10:12:03

+0

@RavishKumar使用位置時出現了什麼問題:絕對 – Sowmya 2013-03-01 10:18:19

+0

我想要的是它應該從頂部和內部主體div中修正20%。 – 2013-03-01 10:20:24

2

兩個選項。只需浮動內部權利,或者使用絕對定位來實現它。

對於浮動只需設置float:right在內部DIV和overflow:隱藏在外部DIV上。

對於絕對定位,只需設置位置:相對於外部DIV和設置位置:絕對和右:0頂部:0在內部DIV上。

+0

這些都不能用'position:fixed'工作,而且我不確定'overflow:hidden'會有什麼幫助。 – 2013-03-01 09:59:19

+0

它使它與頁面對齊而不是外部div – 2013-03-01 10:03:09

+0

@ Twon-ha - 添加overflow:隱藏到包含浮動子元素的父容器允許父容器的高度增長以包含浮動子元素。 – 2013-03-01 10:31:55

1

如果萬一,你想使.inner元素作爲一個固定的定位元素,離開內.outer其他的東西是「滾動」,我建議你設置.inner位置作爲絕對定位的元素。然後,創建後,一個新的包裝與overflow:auto

<div class="outer"> 
    <div class="inner">Some text here...</div> 
    <div class="flow">content</div> <!-- extra markup --> 
</div> 

這裏有一個演示:http://jsfiddle.net/tovic/ZLbqn/3/

1

我認爲這是你想要的

<div class="outer"> 
    <div class="inner">some text here 
    </div> 
</div> 


.outer { 
    margin: 0 auto; 
    width: 860px; 
    direction: rtl; 
    background-color: black; 
    height: 1200px; 
} 

.inner { 
    float: right; 
    position: fixed; 
    text-align: center; 
    width: 220px; 
    background-color: red; 
    height: 50px; 
}