2014-09-23 42 views
0

我有一个边栏设置为位置固定,我也有主要的内容的区域是居中。问题是我想要将内容放在边栏的中心。但是因为它的位置设置为固定的,所以内容仅以身体的整个宽度为中心。CSS position fixed center sibling

我知道这可以通过对身体将居中内容正确设置余量来解决,但我只对某些页面,而不是所有的侧边栏。我创建了一个fiddle来演示整体问题。所以在这里,侧边栏会显示一半的时间,有一半的时间不在那里。但内容的位置总是相同的,这不是我想要的。我希望它以剩余的空闲空间为中心(在边栏(如果存在的话)之后)。

简而言之,我想保持HTML结构(#everything和#content)是静态的,但侧边栏可以做出任何需要的更改以使其工作。

我想也许有侧边栏不固定,但只是无限长的高度,并在它的顶部添加一个位置固定元素,将有内容。通过这种方式,侧栏会将内容移开,并使内容正确居中,同时固定内容。但我不知道如何使侧边栏留在了那里,并无限长......

CSS:

#sidebar { 
    position: fixed; 
    width: 200px; 
    top: 0; 
    bottom: 0; 
    left: 0; 
    border-right: 1px solid #111; 
    padding:5px; 
    background:#f3f3f3; 
} 

#content { 
    width:250px; 
    margin:0 auto; 
} 

回答

1

以下是有点复杂,但你可以尝试以下

#everything{ 
    display:flex; 
} 
#sidebar { 
    width: 200px; 
    height:100%; 
    border:1px solid #ccc; 
} 
#sidebar div{ 
    position: fixed; 
    top: 0; 
    bottom: 0; 
    left: 0; 
    border-right: 1px solid #111; 
    padding:5px; 
    background:#f3f3f3; 
    width: 200px; 
} 
#content { 
    flex:1; 
} 
#content div{ 
    width:250px; 
    margin:0 auto; 

} 

您可以在以下小提琴中找到html部分:JsFiddle

+0

就是这样。谢谢! – Limon 2014-09-23 19:26:23

0

这是很好的例子,用于对齐汽车中心和位置固定

HTML

<div class="popup"> 
    <div class="wrapper"> 
     some content 
    </div> 
</div> 

CSS

.popup{ 
    position:fixed; 
    left:50%; 
} 
.popup .wrapper{ 
    position:relative; 
    left:-50%; 
} 

JsFiddle 快乐:)