這是一道面試題,「頁面上有個元素,只要看不到就好了,問共有多少種方法?」css
隱藏元素,元素不佔用文檔流空間html
設置元素不可見,元素佔用文檔流空間面試
透明度設置爲0,元素正常渲染只是透明。也能夠使用rgba(0,0,0,0)透明通道設置成透明markdown
把元素定位到頁面可視區域之外,使其看不到ui
同4,絕對定位到頁面外,或者其餘元素可視區域之外spa
設置比較低的層級,隱藏到其餘元素下邊3d
使用溢出,隱藏超出可視區域之外的元素code
設置background-color: aliceblue ; color:aliceblue;跟父容器同樣,拿其餘看不出來orm
寬高設置爲0htm
使用transform:scale使用其餘縮小爲0,使其看不到,跟寬高爲0差很少。能夠單獨設置scaleX,scaleY
使用平移使用其移出可視區域外
使用傾斜轉換,在傾斜90度時,就變成一條線,達到隱藏目的
使用X軸旋轉,轉到90度時,也是一條線,使其看不到
同13,只是旋轉軸不同。
同skew同樣,設置3個軸旋轉,再加特定的角度
使用3D旋轉,轉90度,至關於垂直於屏幕,只是一條線。transform:rotate3d(1, 0, 0, 90deg) 也能夠,matrix3d更是無所不能
使用3D旋轉,轉180度,元素背對屏幕,再設置背面不可見
相對定位,再加位移,移到頁面可見區域之外。但DOM仍是存在的,會影響文檔流
以上就是我能想到的隱藏一個元素的方法了,可能還有其餘的,歡迎補充。真實使用時,可能不少方法都用不到,這道題主要仍是考查對樣式的熟練程度,還有遇到一個問題時怎麼去分析,從回答的過程看一我的的思惟。首先把最經常使用的方法答出來;而後是一些奇技淫巧,只是看不到,不算隱藏;再後面是CSS3裏的各類變換,原理都同樣只是寫法不同。
如下是示例頁面截圖和示例代碼,頁腳前面有一堆的元素雖然看不到,但都佔用着頁面空間
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style> .box{ display: block;; width:100px; height: 100px; background-color: #CCC; text-align: center; line-height: 100px; } p{ background-color: aliceblue; width: 500px; height: 300px; position: absolute; top:100px; overflow: hidden; } .box1{ display: none; } .box2{ visibility: hidden; } .box3{ opacity: 0; } .box4{ position: fixed;top:-100%; } .box5{ position: absolute;top:-100%; } .box6{ z-index: -1; } .box7{ margin-top: 300px; } .box8{ background-color: aliceblue ; color:aliceblue; } .box9{ width:0;height: 0 } .box10{ transform: scale(0,0); } .box11{ position: absolute; transform:translateX(-200px); }/* translateY */ .box12{ transform:skew(90deg) } .box13{ transform:rotateX(90deg) } .box14{ transform:rotateY(90deg) } .box15{ transform:rotate3d(1, 1, 1, 120deg) } .box16{ transform:rotate3d(0, 1, 0, 90deg) } .box17{ transform:rotate3d(0, 1, 0, 180deg);backface-visibility: hidden; } .box18{ position: relative; left:-200px;} </style>
</head>
<body>
<h1>如何隱藏頁面上的一個元素</h1>
<div class="box box1">1</div>
<div class="box box2">2</div>
<div class="box box3">3</div>
<div class="box box4">4</div>
<div class="box box5">5</div>
<div class="box box6">6</div>
<div class="box box9"></div>
<div class="box box10">10</div>
<div class="box box11">11</div>
<div class="box box12">12</div>
<div class="box box13">13</div>
<div class="box box14">14</div>
<div class="box box15">15</div>
<div class="box box16">16</div>
<div class="box box17">17</div>
<div class="box box18">18</div>
<p>
這個頁面一共隱藏了17個 box 元素
<span class="box">box</span>
<span class="box box8">8</span>
<span class="box box7">7</span>
</p>
<footer>頁腳</footer>
</body>
</html>
複製代碼