簡體   English   中英

如何在純CSS中做到這一點?

[英]How to do this in pure CSS?

我的頁面右側有一個側邊欄DIV。 側邊欄的CSS

  #sidebar {
    position: fixed;
    right: 0;
    top: 22px;
    border: 3px solid #73AD21;
    max-width: 300px;
    overflow:scroll;
  }

我目前正在使用javascript函數防止頁面主體中的內容與側邊欄重疊

function handleResize() {
    var sbw = document.getElementById('sidebar').offsetWidth;
    var ww = document.documentElement.clientWidth || document.body.clientWidth;
    var bodyWidthVal = 1000;
    $("body").css('width', Math.min(bodyWidthVal,(-9 + ww - sbw)));
}

在檢測到調整大小或縮放的窗口(后者通過鼠標滾輪事件進行捕捉)時,調用此方法。 魔術數字'-9'在某種程度上也是必要的,因為在Web瀏覽器中,我正在使用(IE 11),並且sidebar.offsetWidth不能捕捉到側邊欄邊框的寬度。

這是可行的,但是如果它可以在純CSS中完成,我寧願擺脫這種笨拙的解決方案。

您可以在CSS中應用計算,因此div不會重疊。 例如:

<div class="right-sidebar"></div>
<div class="main-body"></div>

在CSS中:

.right-sidebar{
  position: fixed;
  right: 0;
  top: 0;
  width: 300px;
}
.main-body{
  width: calc(100% - 300px);
  height: 1000px;
}

如果側邊欄的寬度是動態變化的,則可以在JS中獲取寬度,並在JS中相應地更改主體的width屬性。

有一個更簡單的解決方案(實際上有幾個)根本不需要JavaScript。

只需浮動您的內容和側邊欄,然后完成即可。

使用靜態單位只會在特定視口上看起來不錯。 同樣,在CSS中,width和height屬性僅與內容區域的大小有關。 填充,邊框和邊距是超出此范圍的單獨大小。 在CSS中,可以通過以下方式來覆蓋此默認行為box-sizing:border-box在要根據其內容,內邊距和邊框設置box-sizing:border-box任何元素上設置box-sizing:border-box (仍然不包括邊距)。

查看代碼中的注釋:

 /* Change box model default sizing so that padding and borders are counted into the width of an element */ * { box-sizing:border-box; } #wrapper { width:100vw; /* as wide as the viewport */ } #mainContentArea { border:1px solid black; background-color:#e0e0e0; width:80%; float:left; /* align element to left of row allowing next element to float up */ height:100vh; } #sidebar { border:1px solid red; background-color:#808080; width:20%; float:left; /* float to left until another floated element is found */ height:100vh; min-width:100px; /* Don't let the sidebar get smaller than 100px */ } 
 <div id="wrapper"> <div id="mainContentArea"> </div> <div id="sidebar"> </div> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM