|
|
|
|
|
|
在前面文章我們介紹了可以通過使用display隱藏元素,本文將繼續(xù)介紹另一種CSS隱藏元素的方法:使用position。
實例

HTML
<ol class="hide" tabindex="0">
<li>one</li>
<li class="hide-item">two</li>
<li>three</li>
</ol>
<p>鼠標移到任何一個盒子上隱藏盒子two,<br>使用 <b>position: absolute;</b>。</p>
CSS
/* hide element */
.hide:hover .hide-item,
.hide:focus .hide-item {
position: absolute;
left: -999px;
}
/* other styles */
body {
font-family: sans-serif;
font-size: 100%;
color: #222;
background-color: #fff;
}
p {
text-align: center;
}
.hide {
display: flex;
justify-content: center;
list-style-type: none;
padding: 0;
margin: 0;
}
.hide > * {
flex: 0 0 25%;
font-size: 2em;
text-align: center;
padding: 1em 0;
margin: 0.2em;
background-color: #ccc;
border-radius: 0.5em;
user-select: none;
}
.hide-item {
background-color: #f66;
cursor: pointer;
}
代碼解釋
position屬性允許使用top、bottom、left和right將元素從static頁面布局中的默認位置移動。因此,可以將 absolute-positioned 元素移出屏幕,或類似:left: -999px。
| 度量標準 | 影響 |
|---|---|
| 瀏覽器支持 | 非常好,除非使用position: sticky |
| 可訪問性 | 內容仍在閱讀 |
| 布局受影響? | 是的,如果位置改變 |
| 渲染要求 | 看情況 |
| 表現(xiàn) | 謹慎的話是合理的 |
| 動畫幀可能嗎? | 是的,在top, bottom, left, 和right |
| 隱藏時可觸發(fā)事件嗎? | 是的,但可能無法與屏幕外元素交互 |
相關文章
position 屬性
CSS position 屬性用于指定一個元素在文檔中的定位方式。top,right,bottom 和 left 屬性則決定了該元素的最終位置。
relative, absolute, fixed 或 sticky 的一個元素(換句話說,除static以外的任何東西)。大多數(shù)情況下,height和width 被設定為 auto 的絕對定位元素,按其內容大小調整尺寸。但是,被絕對定位的元素可以通過指定top和bottom ,保留height未指定(即auto),來填充可用的垂直空間。它們同樣可以通過指定left 和 right并將width 指定為auto來填充可用的水平空間。
position 屬性被指定為從下面的值列表中選擇的單個關鍵字。
static
該關鍵字指定元素使用正常的布局行為,即元素在文檔常規(guī)流中當前的布局位置。此時 top, right, bottom, left 和 z-index 屬性無效。
relative
該關鍵字下,元素先放置在未添加定位時的位置,再在不改變頁面布局的前提下調整元素位置(因此會在此元素未添加定位時所在位置留下空白)。position:relative 對 table-*-group, table-row, table-column, table-cell, table-caption 元素無效。
absolute
元素會被移出正常文檔流,并不為元素預留空間,通過指定元素相對于最近的非 static 定位祖先元素的偏移,來確定元素位置。絕對定位的元素可以設置外邊距(margins),且不會與其他邊距合并。
fixed
元素會被移出正常文檔流,并不為元素預留空間,而是通過指定元素相對于屏幕視口(viewport)的位置來指定元素位置。元素的位置在屏幕滾動時不會改變。打印時,元素會出現(xiàn)在的每頁的固定位置。fixed 屬性會創(chuàng)建新的層疊上下文。當元素祖先的 transform, perspective 或 filter 屬性非 none 時,容器由視口改為該祖先。
sticky
元素根據正常文檔流進行定位,然后相對它的*最近滾動祖先(nearest scrolling ancestor)*和 containing block (最近塊級祖先 nearest block-level ancestor),包括 table-related 元素,基于top, right, bottom, 和 left的值進行偏移。偏移值不會影響任何其他元素的位置。 該值總是創(chuàng)建一個新的層疊上下文(stacking context)。注意,一個 sticky 元素會“固定”在離它最近的一個擁有“滾動機制”的祖先上(當該祖先的overflow 是 hidden, scroll, auto, 或 overlay時),即便這個祖先不是最近的真實可滾動祖先。這有效地抑制了任何“sticky”行為。
該演示你能夠對黃色盒子控制 position 屬性。
看 sticky 位置效果,選擇 position: sticky 選項和滾動容器。元素將與其容器一起滾動,直到它位于容器的頂部(或達到top中指定的偏移量),然后將停止?jié)L動,使其保持可見。
position: sticky;
top: 20px;

position: static;
position: relative;
top: 40px; left: 40px;
position: absolute;
top: 40px; left: 40px;

相關文章
