【问题标题】:CSS position fixed center siblingCSS位置固定中心兄弟
【发布时间】:2023-03-29 07:04:03
【问题描述】:

我有一个设置为固定位置的 sidebar,我还有一个居中的主要 content 区域。问题是我想将关于侧边栏的内容居中。但是因为它的位置被设置为固定,content 只在 body 的整个宽度上居中。

我知道这可以通过为主体设置边距来解决,这将使 content 正确居中,但我只有 sidebar 在某些页面上而不是全部.我创建了一个fiddle 来演示整个问题。所以在这里,一半的时间侧边栏会出现,一半的时间不会出现。但是 content 的位置总是一样的,这不是我想要的。我希望它以剩余的可用空间为中心(在 sidebar 之后(如果存在))。

简而言之,我想让 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;
}

【问题讨论】:

    标签: html css css-position centering


    【解决方案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中找到

    【讨论】:

      【解决方案2】:

      这是对齐自动中心和固定位置的非常好的简单示例

      HTML

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

      CSS

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

      示例

      JsFiddle 开心就好:)

      【讨论】:

        猜你喜欢
        • 2012-05-24
        • 1970-01-01
        • 2016-01-12
        • 1970-01-01
        • 2013-02-05
        • 1970-01-01
        • 2018-05-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多