2014-08-31 92 views
2

我使用position:fixed < div創建了一個簡單標記div >具有兩個超鏈接的標頭。接下來,我希望該div動態匹配頁面內容的寬度。確定位置:在CSS上以像素爲單位固定div動態寬度

這裏的問題是頁面內容的尺寸是由像素中設置的主體元素的填充控制的。

這裏是描述的情況小提琴:http://jsfiddle.net/jn7z1wke/2/

谷歌搜索說,固定元素的寬度可以以百分比動態控制(如它在小提琴width: 95%;顯示,但不解決我的問題 - 我需要固定div的寬度以像素爲單位進行動態調整

我完全知道如何做到這一點的JS/JQuery的,但最終我想這樣做,在普通CSS

回答

2

你可以使用calc()。減去填充3210。

Updated Example

.fixedheader { 
    position: fixed; 
    background: none repeat scroll red; 
    width: calc(100% - 40px); 
} 

calc()瀏覽器支持可以看出here


另外,剛剛成立right:20px/left:20px

Example Here

.fixedheader { 
    position: fixed; 
    background: none repeat scroll red; 
    right:20px; 
    left:20px; 
} 
+0

+1沒有什麼別的I C一個做大聲笑... :) – Anonymous 2014-08-31 19:59:36

+0

謝謝!........;) – Anonymous 2014-08-31 20:01:30

+2

這兩個選項在我的生產工作。 calc(100%-40px)是一個非常不錯的lifehack,雖然:) – 2014-08-31 20:07:07

2

SET padding: 0px 2.5%;身體 - DEMO

.fixedheader{ 
    position: fixed; 
    background: none repeat scroll red; 
    width: 95%; /* this has to be changed and match the width of the .content on window resize */ 
} 

.content{ 
    background: none repeat scroll 0% 0% #A0A2A7; 
    padding-top: 20px; 
} 

body 
{ 
    margin: 0; 
    padding: 0 2.5%; 
    background: none repeat scroll 0% 0% #C2BAC1; 
} 
+0

雖然有效,但我認爲OP需要'body'元素的填充位置設置爲'px'單位也不是百分比。 – 2014-08-31 19:52:08

+0

@JoshCrozier糟糕!等待...... – Anonymous 2014-08-31 19:53:41