2014-08-31 91 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