CSS

[CSS] display : none vs visibility: hidden

해봄코딩 2023. 2. 16. 20:46

 

 

CSS에서 엘리멘트를 숨길 때  display: none 과 visibility : hidden를 사용할 수가  있습니다. 

그런데 이 둘의 차이점이 뭔지 궁금해서 알아보았습니다. 

 

일단 이런 상자가 있다고 칩시다. 주황, 파랑, 청록색 블럭이 있네요! (결과값쪽을 봐주세요) 

 

 

 

먼저 display : none에 대해 알아봅시다! 

display속성은 어떻게  엘리먼트가 표시되는지 결정합니다. (inline or block 중) 

그리고 flex, grid등과 같은 엘리먼트의 자식들의 레이아웃도 설정합니다. 

이때, display를 none와 함께 쓰면 엘리먼트를 보여주지 않습니다. (게다가 그 자식들까지 포함해서) 

마치 원래 없는 것처럼요!! 😮😮😮

 

위의 예시에서 class  block2를 'display: none'으로 바꾸면 

.block2 {
  background-color: rgb(77, 77, 234);
  margin-right: 20px;
  display: none;
}

 

가운데 파란색 블럭 뿐만 아니라 차지했던 공간도 사라졌습니다!!! 😮😮😮

 

 

다음은 visiblity : hidden입니다. 

visibility 속성은 이름처럼 엘리먼트를 보여줄지 아닐지를 지정합니다. 

그러니까  엘리먼트의 레이아웃에 영향을 끼치지 않습니다.

이 부분이 display : none과 비교하면 가장 큰 차이점이네요! 

레이아웃은 유지된채 엘리먼트만 보이지 않게 해줍니다. 

 

 

 

정리하자면 

둘 다 엘리먼트를 보여주지 않지만,

display: none은 엘리먼트와 공간까지 없애버리고 

visibility :hidden은 엘리먼트만 보여주지 않는다고 이해하면 될 것 같네요! 

 

 

이 내용은 짧은영어로 아래 문서를 보고 요약했습니다. 

https://www.freecodecamp.org/news/css-display-none-and-visibility-hidden-the-difference/

 

CSS display:none and visibility:hidden – What's the Difference?

display:none and visibility:hidden are two style declarations you can use to hide elements on the screen with CSS. But what are the differences between them? When building applications, there are times that you want to hide elements visually (not deleting

www.freecodecamp.org