CSS隱藏的方式有哪些?display:none,opacity:0,visibility: hidden有什麼不同

來源:互聯網
上載者:User
我們在寫頁面時,經常會用到隱藏,隱藏有哪些方法,他們都有什麼不同呢?
你可以將 opacity 值設為 0、將 visibility 設為 hidden 或者 display 設為 none 。但是每一種方法都有不同之處,這些不同可以讓我們在一個特定的場合下做出正確的選擇。下面這篇文章就和大家聊聊他們的區別,讓大家能根據場合來選擇合適的方式。

1.display:none
將 display 屬性設為 none ,使用這個屬性,被隱藏的元素不佔據任何空間。這種方式產生的效果就像元素完全不存在,這個元素的子孫元素也會被同時隱藏。即該元素在頁面上徹底消失,通俗來說就是看不見也摸不到。
舉例:使用樣式“display:none”隱藏元素

<!DOCTYPE html><html> <head>  <meta charset="UTF-8">  <title></title>  <style type="text/css">   .a1{width: 100px;height: 100px;background: red;display: none;}   .a2{width: 100px;height: 100px;background: yellow;}  </style> </head> <body>  <div class="a1">have a nice day</div>  <div class="a2">have a nice day</div> </body></html>

2、opacity
該屬性的是設定對象的不透明度,當他的透明度為0的時候,視覺上它是消失了,但是他依然佔據著那個位置,通俗來說就是看不見但摸得到。並對網頁的布局起作用,添加了該屬性的元素,它的背景和元素內容也是會跟著變化的。
舉例:使用樣式“opacity:0”隱藏元素

<!DOCTYPE html><html> <head>  <meta charset="UTF-8">  <title></title>  <style type="text/css">   .a1{width: 100px;height: 100px;background: red;opacity: 0;}   .a2{width: 100px;height: 100px;background: yellow;}  </style> </head> <body>  <div class="a1">have a nice day</div>  <div class="a2">have a nice day</div> </body></html>

3、visibility: hidden
將該屬性值設為hidden的時候,元素將會隱藏,但該對象在網頁上所佔的空間沒有改變,通俗來說就是看不見但摸得到。並對網頁的布局起作用,該屬性類似opacity屬性,但與 opacity 唯一不同的是它不會響應任何使用者互動。
舉例:使用樣式“visibility: hidden”隱藏元素

<!DOCTYPE html><html> <head>  <meta charset="UTF-8">  <title></title>  <style type="text/css">   .a1{width: 100px;height: 100px;background: red;visibility: hidden;}   .a2{width: 100px;height: 100px;background: yellow;}  </style> </head> <body>  <div class="a1">have a nice day</div>  <div class="a2">have a nice day</div> </body></html>

以上介紹了3種隱藏的方法,每種方法之間都有所不同,在實際項目中,到底應該用哪種,就要視情況而定了。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.