css 如何使侧边栏顶部的标题,而双方作为固定的位置?

cmssoen2  于 2022-12-24  发布在  其他
关注(0)|答案(2)|浏览(143)

HTML代码:

<div id="screenLeft" class="screen"></div>
<div id="screenTop" class="screen"></div>


<div id="container">
    
    <div id="content">
        Test Possition of Text and whatnot1<br />
        Test Possition of Text and whatnot2<br />
        Test Possition of Text and whatnot3<br />
        Test Possition of Text and whatnot4<br />
                  

    </div>
    
</div>

CSS代码:

.screen {
    position: fixed;
    background: black;
}
#screenTop {
    height: 100px;
    width: 100%;
    background: green;
}
#screenLeft {
    height: 100%;
    width: 100px;
}
#screenTop { top: 0; }
#screenLeft { left: 0; }

#content {
    margin: 100px;
}

"我有两个问题"

  • 我怎样才能把黑色侧边栏的顶部标题,而这两个是固定的?
  • 如果边栏和标题没有显示,我如何在整个屏幕上显示内容div?

enter image description here

z8dt9xmd

z8dt9xmd1#

第一个问题:
当标题和侧边栏的位置都固定时,如何在标题顶部显示侧边栏?
答案很简单,您可以使用z-index = number(例如,z索引= 100),
参考:MDN

    • z-index CSS属性**设置定位元素及其后代的顺序。具有较大z-index的重叠元素覆盖具有较小z-index的重叠元素。

示例代码:

.screen {
    position: fixed;
    start: 0;
}
#screenTop {
    height: 100px;
    width: 100%;
    top: 0;
    z-index:10;
}
#screenLeft {
    height: 100%;
    width: 100px;
    top:100px; /*To Prevent Overlapping*/
    z-index:9;
}
#content{
    margin: 50px;
}

第二个问题:
如果边栏和标题没有显示,我如何在整个屏幕上显示内容div?
您将需要使用一点javascript来执行此操作,
将以下代码添加到<body>标记的末尾,
然后根据您的需要进行修改。

<script>
    function ToggleContent()
    {
        let screenTopDisplay = document.getElementById("screenTop").style.display;
        let screenLeftDisplay = document.getElementById("screenLeft").style.display;
        
        let toggleMargin =
            (screenTopDisplay = "" || screenTopDisplay = "block") && (screenLeftDisplay = "" || screenLeftDisplay = "block");
        
        let container = document.getElementById("container");
        
        if(toggleMargin)
        {
            container.style.margin = "100px 0px 0px 100px";
        }
        else
        {
            container.style.margin = "0px";
        }
    
    }
</script>
  • 当您显示/隐藏. screen ToggleContent()时,请记住调用该函数
mf98qq94

mf98qq942#

对于您的第一个问题,将这2个属性top:0px;(从屏幕的0开始)和z-index:99;(堆叠在顶栏上)添加到侧栏id #screenLeft
对于您的第二个问题后,删除侧边栏和顶栏添加此css #content { margin-left: 0; margin-top: 0; },它将删除边距形式的内容div。

.screen {
    position: fixed;
    background: black;
}
#screenTop {
    height: 100px;
    width: 100%;
    background: green;
}
#screenLeft {
    height: 100%;
    width: 100px;
    top:0;
    z-index:99;
}
#screenTop { top: 0; }
#screenLeft { left: 0; }

#content {
    margin: 100px;
}
<div id="screenLeft" class="screen"></div>
<div id="screenTop" class="screen"></div>


<div id="container">
    
    <div id="content">
        Test Possition of Text and whatnot1<br />
        Test Possition of Text and whatnot2<br />
        Test Possition of Text and whatnot3<br />
        Test Possition of Text and whatnot4<br />
                  

    </div>
    
</div>

相关问题