[英]How to make a div scroll if the text overflows HTML/CSS? (without fixed height)?
[英]How can I make a div, which is bigger (in height) then the window, be fixed but still scroll able without any sidebar?
我在網上可以找到的最好的例子就是這個Yahoo頁面。 右邊的div是固定的。 但是,每當我向上滾動時,它就一直將頁面滾動到頂部,而當我向下滾動時,它會滾動到div的底部。
到目前為止,我設法創建了以下代碼:
.sidediv{ height: 1000px; position: fixed; max-height: 100%; overflow-y: auto; } #content{ height: 2000px; background: green; width: 300px; } #left{ height:1000px; background: yellow; float: left; width: 120px; } #right{ width: 120px; background: blue; float: left; height: 100%; }
<div id="content"> <div id="left"> Left side, main content </div> <div id="right"> <div class="sidediv"> Side content here </div> </div> </div>
謝謝
我很確定Yahoo! 頁面使用JavaScript來實現效果,但是(如果我正確理解了您的請求)只能使用CSS來實現。
position
CSS屬性有一個相當新的值,即position: sticky
。 請允許我給您一個實際的例子(模擬我認為是您的要求):
aside { position: sticky; /* Oh yeah! Sticky! */ top: 0; /* Distance from top when it's stuck. Play around with this value a bit */ background-color: #B8c1c8; padding: 10px; height: 100px; width: 30%; margin-left: auto; box-sizing: border-box; } body { margin: 0; } header { height: 50px; background-color: #ddd; } nav { position: absolute; height: 100px; top: 50px; width: 100%; background-color: #eee; } article { border-bottom: 1px solid #ccc; padding: 10px; }
<header>HEADER! Awesome! </header> <nav>NAVIGATION BAR! Awesome!</nav> <div> <aside>STICKY SIDE! Awesome!</aside> <article> <h2> Scroll the page down </h2> <p> to see the effect </p> </article> <article> <h2> Title! </h2> <p> Potatoes! </p> </article> <article> <h2> Title! </h2> <p> Potatoes! </p> </article> <article> <h2> Title! </h2> <p> Potatoes! </p> </article> <article> <h2> Title! </h2> <p> Potatoes! </p> </article> </div>
基本上,這使它可以使元素在您向下滾動時停留在頁面上,但僅當您向下滾動時才保留。 如果不這樣做,它的行為正常。
但是, 瀏覽器對其的支持似乎不太好。 Internet Explorer,Edge,Chrome 55和大多數移動瀏覽器根本不支持它,這是一個遺憾。 希望幾年后它將成為標准。
希望這對您仍然有意義! 干杯!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.