2014-12-04 75 views
0

我想包裝一個固定位置的子元素在父div沒有它打破了div。我如何使一個固定位置的子div包裝在一個固定寬度的父div內

我希望它的行爲像不是固定的div,但我需要修復子元素並自動換行或調整大小,因爲我將需要它作爲響應站點。所以這就是爲什麼我真的不希望做一個溢出的情況,如果有可能,我會在有固定的div

HTML

<div class="parent"> 
    <div class="child">I am a child div with a 100% width</div> 
</div> 


<div class="parent"> 
    <div class="child-unfixed">I am a child div that is unfixed (this is the desired affect I am after but using a fixed position if possible)</div> 
</div> 

CSS

.parent { 
    background:green; 
    padding:20px; 
    margin-bottom:20px; 
    margin-right:100px; 
    width:200px 
} 

.child { 
    background:yellow; 
    position:fixed; 
    width:100%; 
    text-align:right; 
} 
.child-unfixed { 
    background:pink; 
} 

Here is the JSfiddle右對齊內容

+0

除去母體div的最大寬度? – nCore 2014-12-04 14:35:00

+0

固定位置與絕對位置相似。他們需要頂部,左側,右側,底部。這可能不是你想要的。我會看看這篇關於職位的文章http://css-tricks.com/absolute-relative-fixed-positioining-how-do-they-differ/ – 2014-12-04 14:36:27

+0

和其他人一樣,使用「固定」定位的問題是它將元素從流中取出。因此,你不能將它的父母放在它的周圍,因爲它好像沒有它。 – Marcelo 2014-12-04 14:38:22

回答

1

position: fixed;不能在div之內。它堅持到窗口,不能堅持HTML元素。

developer.mozilla.org

固定

不要爲元素留出空間。相反,將其放置在相對於屏幕視口的指定位置,並且在滾動時不要移動它。打印時,將其放在每頁上的固定位置。

0

http://jsfiddle.net/tLbggwp8/11/

嘗試取出position:fixed;作爲另一個答案指示,然後設置max-width設置到父DIV和填充的差異。

手動我設置爲460px(每邊20px填充)。

一些其他的東西,你可以工作,幫助佈局:

  • calc [最大寬度:理論值(XY)]的使用功能來計算max-width更具動態使用
  • box-sizing:border-box;協助與填充和邊距尺寸
0

的最終計算中包含起初我沒想到該地區的實際尺寸會有這樣的一種方式,因爲它就像一個絕對的div和採取頁面的元素。

但它似乎繼承的寬度訣竅。

width: inherit; 

http://jsfiddle.net/susannalarsen/tLbggwp8/12/