상세 컨텐츠

본문 제목

[번역] Guide to hiding elements in CSS

개발 공부/Translation

by Ryomi 2024. 1. 24. 17:29

본문

반응형

Hiding website elements can be useful for a variety of reasons, such as protecting sensitive information, restricting access to premium content, or personalizing content for specific user groups. For example, we may want to hide certain promotions or offers from users who have already made a purchase or personalize content based on a user’s geographic location or browsing history. We can use CSS to selectively hide or show certain elements based on user attributes.

웹사이트 요소를 숨기는 것은 민감한 정보 보호, 프리미엄 컨텐츠로의 접근 제한, 특정 사용자 집단을 위한 컨텐츠 개인화와 같은 다양한 이유로 유용할 수 있습니다. 예를들어, 사용자가 이미 구매한 경우 특정 프로모션이나 제안을 숨기거나 사용자의 지리적 위치나 브라우징 기록에 따라 컨텐츠를 개인 맞춤화하는 경우입니다. 사용자 속성에 따라 CSS를 사용해 특정 요소를 선택적으로 보여주거나 숨길 수 있습니다. 

 

For a long time, using display: none was a popular method to hide elements, but now there are more versatile and animatable options available. In this article, we’ll explore six additional CSS properties that may be used to hide elements and analyze the tradeoffs of each approach. Whether you’re a beginner or an experienced developer, this guide will provide you with best practices for hiding elements on your webpages.

오랬동안, 'display: none'을 사용하는 것은 요소를 숨기는 인기있는 방법이었지만, 현재는 더 다양하고 애니메이션 가능한 옵션이 있습니다. 이 글에서, 요소를 숨기는데 사용할 수 있는 6개의 추가적인 CSS 속성을 알아보며 각각의 접근방식의 장단점을 분석합니다. 당신이 초보자든 경험이 있는 개발자든 상관없이, 이 가이드는 웹 페이지에서 요소를 숨기는데 사용되는 최상의 방법을 제공할 것입니다. 

 

Tradeoffs to consider when using CSS to hide an element

요소를 숨기 위해 CSS를 사용할 때 고려해야 할 장단점들

 

There are multiple ways to hide an element with CSS, but they differ in the way they affect layout, animation, event handling, performance, and accessibility. Here’s some information to keep in mind if you’re considering hiding elements on a webpage:

CSS로 요소를 숨기는 많은 방법들이 있지만, 이들이 레이아웃, 애니메이션, 이벤트 핸들링, 성능, 그리고 접근성에 미치는 영향은 다릅니다. 웹 페이지에서 요소를 숨길때 다음 정보를 참고하세요.

 

  • Animation: Some CSS properties can be animated in-between states; however, others cannot be animated and just go from being visible to invisible without a gradual fade-out or any other animation.

Animation: 일부 CSS 속성들은 중간상태에서 애니메이션을 적용할 수 있지만, 다른 속성들은 애니메이션을 적용할 수 없고 서서히 사라지거나 다른 애니메이션 없이 단순히 보이는 상태에서 사라지는 것으로 전환됩니다. 

N.B., animations can cause physical discomfort, such as migraines, seizures, or disorientation, for certain people. As a result, it is recommended to use the prefers-reduced-motion media query to disable animations when users have specified this preference

참고: 애니메이션은 특정 사용자들에게 두통, 경련, 방향감각 혼란 등과 같은 육체적인 불편을 야기할 수 있습니다. 그 결과로 사용자가 이러한 기호를 지정한 경우, 'prefer-reduced-motion' 미디어쿼리를 사용해 애니메이션을 비활성화하는 것이 권장됩니다. 

 

  • Event handling: Some CSS properties do not allow events to be triggered on a hidden element. Others have no effect, meaning an invisible element could still be clicked on to trigger an event

Event handling: 일부 CSS 속성들은 숨겨진 요소에서 이벤트를 트리거할 수 없게 합니다. 다른 속성들은 이벤트에 영향을 주지 않습니다. 이는 보이지 않는 요소는 이벤트를 발생시키기 위해 여전히 클릭될 수 있음을 의미합니다. 

 

  • Performance: Many of the approaches discussed in this article may negatively impact the performance of a webpage, particularly those that impact layout rather than just composition. This makes sense if we consider how a webpage is rendered. Once the HTML DOM and CSS object model are loaded and parsed by a browser, the webpage undergoes three stages of rendering:
    • Layout: the size and position of each element are determined
    • Paint: each element’s pixels are drawn
    • Composition: the layers of elements are arranged in the correct order

성능: 이 글에서 이야기된 접근 방식 중 많은 방식은 웹 페이지의 성능에 부정적 영향을 미칠 수 있습니다. 특히 단지 구성이 아닌 레이아웃에 영향을 미치는 방식은 더욱 그렇습니다. 이는 웹 페이지가 어떻게 렌더링되는지를 고려하면 이해할 수 있습니다. 일단 HTML DOM과 CSS 객체 모델이 브라우저에 의해 로드된 후 파싱되면, 웹 페이지는 3단계의 렌더링과정을 거칩니다.

  • 레이아웃: 각 요소의 크기와 위치가 결정됩니다.
  • 페인트: 각 요소의 픽셀이 그려집니다.
  • 구성: 요소의 레이어가 올바른 순서로 배치됩니다. 

 

  • Accessibility: The techniques discussed in this article can make an element invisible on the screen, but do not always hide its content from assistive technologies. For example, screen readers can still read out transparent text. ARIA attributes like aria-hidden="true" may need to be added to correctly describe the current state of the element

접근성: 이 글에서 논의된 기술들은 요소가 스크린에서 보이지 않게 할 수 있지만 항상 보조 기술들로부터 요소의 컨텐츠를 숨기지는 못합니다. 예를 들어 스크린 리더는 투명한 글자를 여전히 읽을 수 있습니다. 'aria-hidden='true''처럼  ARIA 속성은 요소의 현재 상태를 올바르게 설명하기 위해 추가되야 할 수도 있습니다. 

 

CSS display property

The CSS display property determines if an element should be treated as a block or inline element and also sets the layout for its child elements, such as flex or grid.

 CSS display 속성은 요소가 블록 또는 인라인 요소로 처리해야 하는지 결정하고 flex, grid 처럼 자식 요소들의 레이아웃을 설정합니다.

We can use the display property with a value of none to hide elements and their descendants on a webpage:

웹 페이지에서 요소와 요소의 자식 요소를 숨기기 위해 속성값이 'none'인 display 속성을 사용할 수 있습니다. 

.hide-element{
   display:none;
}

Setting a display value of none on an element removes it from the layout completely, making it appear as though it doesn’t exist in the document. This also applies to its child elements.

요소에 display값을 'none'으로 설정하면 마치 문서에 존재하지 않는것 처럼 해당 요소는 레이아웃에서 완전히 제거됩니다. 이는 또한 자식 요소에도 적용됩니다. 

In the below example, we hide the div element and the button element immediately moves to the div‘s former position. We can see that the div is removed entirely from the layout when its display property is set to none:

아래 예시에서, div 요소를 숨기고 버튼요소는 즉시 div의 이전 위치로 이동하게 합니다. div tag의 display 속성이  none으로 설정되면 레이아웃에서 완전히 제거되는 것을 볼 수 있습니다. 

Animatable

It is not possible to animate the display property values directly, because display only accepts certain values (e.g., block, inline, inline-block) and cannot be transitioned or animated like other properties that accept numeric or color values.

display 속성값에 직접 애니메이션을 적용하는 것은 불가능합니다. display는 특정 값만 허용하며, 숫자나 색상값을 받는 다른 속성들 처럼 전환이나 애니메이션화 될 수 없습니다.

Trigger events

When an element is hidden using the display: none approach, it is removed from the page layout and the browser does not allocate any resources to the element. This means that events cannot be triggered on the element.

요소가 'display: none'을 사용해 숨겨지면 페이지 레이아웃에서 제거되고 브라우저는 해당 요소에 어떤 자원도 할당하지 않습니다. 이는 해당 요소에 이벤트가 발생될 수 없음을 의미합니다.

Performance

Setting an element’s display property to none could lead to layout thrashing or delayed content rendering.

요소의 display 속성을 none으로 설정하는 것은 layout thrashing 또는 컨텐츠 렌더링의 지연을 야기할 수 있습니다.

Accessibility

Hiding an element with display: none excludes it from the accessibility tree, making it inaccessible to assistive technologies. Consequently, the element and its child elements will not be read by screen readers.

display: none으로 요소를 숨기면 접근성 트리에서 제외되어 보조 기술이 해당 요소에 접근할 수 없게 됩니다. 결국, 해당 요소와 자식 요소는 스크린 리더에 의해 읽히지 않습니다.

 

visibility property

The CSS visibility property permits an element to be hidden or shown without altering the document’s layout. This property can be used to hide rows or columns in a <table> as well:

CSS visibility 속성은 문서의 레이아웃 변경 없이 요소가 나타나고 숨겨지게 합니다. 이 속성은 table 요소의 열이나 행을 숨기는데도 사용될 수 있습니다.

.hide-element{
  visibility: hidden;
}

In the below example, we hide a div element using the visibility property. This approach only hides the element visually, it is not removed from the document and the document’s layout is not altered:

아래 예시에서, visibility 속성을 사용해 div 요소를 숨깁니다 이러한 접근 요소를 시각적으로만 숨기며, 요소가 문서에서 제거되지 않고 문서의 레이아웃을 변경하지 않습니다.

 

Animatable

It is possible to animate the visibility property, but the result looks terrible and gives a jarring effect. This is because the visibility property has a binary value of visible and hidden. When transitioning between these two states, the element will appear or disappear abruptly without any intermediate states.

visibility 속성을 애니메이션화 하는 것은 가능하지만 결과물은 형편없어 보이고 부자연스러운 결과를 야기합니다. 이는 visibility 속성이 visible과 hidden이라는 두 개의 값을 가지기 때문입니다. 이 두 상태 사이를 전환할 때, 요소는 중간상태 없이 갑자기 나타나거나 사라집니다.

Trigger events

When an element is hidden using the visibility: hidden approach, it is still present in the page’s DOM and can receive events, such as clicks, hovers, or keyboard events. However, since the element is not visible, it’s difficult for the user to interact with it.

요소가 visibility: hidden으로 숨겨지면, 해당 요소는 여전히 페이지의 DOM에 존재하며 click, hover 또는 키보드 이벤트와 같은 이벤트를 받을 수 있습니다. 그러나 요소가 보이지 않기 때문에 사용자가 해당 요소와 상호작용하는것은 힘듦니다.

Performance

Setting an element’s visibility property to hidden has a negligible effect on performance, because it only affects the element’s visual rendering — not its layout or size.

요소의 visibility 속성을 hidden으로 설정하는 것은 요소의 레이아웃이나 크기가 아닌 시각적 렌더링에만 영향을 미치므로 성능에는 미미한 영향을 미칩니다.

However, if an element has a complex rendering, or contains many child elements, setting its visibility to hidden may still impact performance due to the browser’s rendering engine needing to calculate and process the element’s styles and properties.

그러나, 요소가 복잡한 렌더링을 가지거나 많은 자식요소를 포함하고 있다면, visibility 속성을 hidden으로 설정하는 것은 여전히 성능에 영향을 줄 수 있습니다. 이는 브라우저의 렌더링엔진이 요소의 스타일과 속성을 계산하고 처리해야하기 때문입니다.

Accessibility

When an element is hidden with visibility: hidden it is still present in the HTML code and is still available to screen readers. However, the content of the hidden element is not visible on the screen, which can cause issues for users who rely on visual cues to navigate the page.

visibility: hidden 으로 요소를 숨기면, 해당요소는 여전히  HTML 코드에 존재하며 스크린리더가 읽을 수 있습니다. 그러나, 숨겨진 요소의 컨텐츠는 화면에 보이지 않으며, 이는 페이지를 탐색하기 위해 시각적 단서에 의존하는 사용자들에게 문제가 될 수 있습니다.

 

 

opacity and filter properties

The CSS opacity property determines an element’s level of transparency by controlling the extent to which content located behind an element is concealed. opacity is essentially the inverse of transparency.

CSS opacity 속성은 요소의 투명도를 결정하여 해당 요소의 뒤에 있는 컨텐츠가 감춰지는 정도를 조절합니다. opacity는 투명도의 반대입니다. 

We can achieve the same effect with the filter: opacity() property, but it’s generally preferable to use the opacity property and then retain the filter for other uses (e.g., applying blur, contrast, or grayscale effects on elements). The choice is yours.

filter: opacity() 속성을 사용해 동일한 효과를 얻을 수 있지만, 일반적으로 opacity 속성을 사용하고 다른 용도(요소에 blur, contrast, grayscale 효과 적용)를 위해 filter를 사용하는 것이 선호됩니다.  

.hide-element{
  opacity: 0.3;
  // or
  opacity: 30%;

  // or
  filter: opacity(0.3);

  // or
  filter: blur(100px);
}

The opacity property’s value is represented by a number between 0.0-1.0 or a percentage between 0% to 100%. This signifies the opacity of the channel or the value of its alpha channel. Values outside of this range are still acceptable but will be limited to the nearest boundary within the specified range.

opacity 속성의 값은 0.0~1.0 사이의 숫자나  0~100% 사이의 백분율로 표현됩니다. 이는 채널의 투명도나 알파 채널의 값에 해당합니다. 범위를 벗어난 값은 여전히 허용되지만 지정된 범위 내에서 가장 가까운 경계로 제한됩니다. 

Opacity affects the entire element, including its contents. This means that the element and its children will have the same level of opacity in relation to the background of the element, regardless of their individual opacities relative to each other.

opacity는 요소의 컨텐츠를 포함해 전체 요소에 영향을 미칩니다. 즉, 요소와 요소의 자식요소는 서로의 투명도와는 관계없이 요소의 배경에 대한 동일한 투명도를 가지게 됩니다.

N.B., if an opacity value other than 1 is used, it creates a new stacking context for the element.

참고: opacity값이 1이 아닌 경우, 해당 요소에 새로운 쌓임 맥락을 생성합니다.

 

In the below example, we hide a div element using the opacity property:

아래 예시에서, opacity 속성을 사용해 div 요소를 숨깁니다.

 

Animatable

Any element that is hidden with the opacity property can still be animated. By gradually changing the opacity value from 1 (fully visible) to 0 (fully transparent), the element will gradually fade-out and become hidden. Similarly, by gradually changing the opacity value from 0 to 1, the element will gradually fade-in and become visible.

opacity 속성으로 숨겨진 요소는 여전히 애니메이션화 될 수 있습니다. 1에서 0으로 점진적으로 opacity 값을 바꿈으로써 요소는 점점 사라져 숨겨집니다. 비슷하게, opacity 값을 0에서 1로 점진적으로 변경함으로써 요소는 서서히 나타나면서 보이게 됩니다. 

Trigger events

When an element is hidden using the opacity approach, events can still be triggered on that element. This is because the element is still present in the document and still occupies space in the layout, even though it is not visible.

요소가 opacity를 사용해 숨겨지면, 해당요소에 이벤트는 여전히 발생할 수 있습니다. 이는 요소가 보이지 않더라도, 여전히 문서에 존재하여 레이아웃에서 공간을 차지하기 때문입니다.

Performance

Hiding an element using opacity, has no significant impact on performance.

opacity를 사용해 요소를 숨기는 것은 성능에 큰 영향을 미치지 않습니다. 

Accessibility

When an element is hidden using opacity, it is still present in the document and still occupies space in the layout, which means that it can still be detected by screen readers and other assistive technologies. However, if the hidden element is not properly labeled, or if it is not reachable using keyboard navigation, it can be difficult for visually-impaired users to access and understand the content on the page.

opacity를 사용해 요소를 숨길 때, 해당 요소는 여전히 문서에 존재하며 레이아웃에서 여전히 영역을 차지하므로 해당요소가 여전히 스크린 리더와 보조 도구에 의해 감지될 수 있습니다. 그러나, 숨겨진 요소가 적절하게 라벨링 되어있지 않거나, 키보드 네비게이션으로 접근할 수 없다면 이는 시각적으로 손상된 사용자들이 페이지 내용에 접근하고 이해하는것을 어렵게 할 수 있습니다.

 

 

clip-path property

The CSS clip-path property allows us to define a specific region of an element that should be displayed while hiding the remaining parts. The clipping region determines which part of the element is visible, while the parts that fall outside the region are hidden from view:

CSS clip-path 속성은 요소의 특정 영역을 정의하여 해당 부분은 나타내고 나머지 부분은 숨길 수 있습니다. clipping 영역은 영역의 바깥부분이 숨겨지게하면서 요소의 어떤 부분이 보이는지를 결정합니다. 

.hide-element{
   clip-path: polygon(0 0, 0 0, 0 0, 0 0);

    //or 

    clip-path: circle(0);
}

In the above code, the clip-path property is set to a polygon with four points, all of which are at the origin (0, 0), effectively hiding the element.

위 코드에서,  clip-path 속성은 네개의 점이 모두 원점(0, 0)에 위치한 다각형으로 설정되어 있어 효과적으로 요소를 숨깁니다.

In the below example, we hide a div element using the clip-path property set to a circle:

아래 예시에서, clip-path 속성을 원 모양으로 설정해 div 요소를 숨깁니다.

 

Animatable

The clip-path property can be animated using CSS animations and transitions to create interesting visual effects.

clip-path 속성은 흥미로운 시각 효과를 만들기 위해 CSS  애니메이션과 transition을 사용해 애니메이션화 될 수 있습니다.

Trigger events

Events can be triggered on an element that is hidden using the CSS clip-path property. Even though the element is not visible, it still exists in the document and can respond to events like clicks, hovers, and key presses.

CSS clip-path를 사용해 숨겨진 요소에 이벤트를 발생시킬 수 있습니다. 요소가 보이지는 않지만, 여전히 문서에 존재하며 클릭, hover, 키 누름과 같은 이벤트에 반응할 수 있습니다.

Performance

Using clip-path to hide elements can have an impact on performance, particularly when the property is animated.

요소를 숨기기 위해  clip-path를 사용하는 것은 특히 속성이 애니메이션화되어있을 때 성능에 영향을 미칠 수 있습니다.

Animating an element’s clip-path property requires the browser to recalculate the layout and repaint the element for each frame of the animation. This can be a very resource-intensive process and can cause the animation to be choppy or laggy on slower devices, particularly if multiple elements are being animated with clip-path simultaneously.

요소의  clip-path 속성을 애니메이션화 하는 것은 브라우저가 layout을 다시 계산하고 애니메이션의 각 프레임마다 요소를 다시 색칠하는 것을 요구합니다. 이는 매우 리소스가 집중된 과정이며, 특히나 여러 요소가 동시에 clip-path로 애니메이션화 되어있다면, 느린 기기에서 뚝뚝 끊어지고 속도 지연을 야기할 수 있습니다.

Hiding elements with the clip-path approach can also affect the overall page layout; other webpage elements may shift or resize as the clipped elements are revealed or hidden. This can lead to a reduction in the quality and predictability of the user experience.

clip-path로 요소를 숨기는 것은 또한 전체적인 페이지 레이아웃에 영향을 미칠 수 있습니다. clipped 요소가 나타나거나 사라지면 다른 웹 페이지 요소는 이동되거나 크기가 조정될수도 있습니다.

Accessibility

When content is hidden using clip-path, it is still present in the document and can be accessed by screen readers and other assistive technology. However, if the hidden content is not properly labeled or described, visually impaired users may not be aware of its presence and may miss out on important information or functionality.

컨텐츠가 clip-path를 사용해 숨겨지면, 해당 요소는 여전히 문서에 존재하며 스크린 리더와 다른 보조 기술이 접근할 수 있습니다. 그러나 숨겨진 컨텐츠가 적절하게 라벨링 되거나 묘사되지 않으면, 시각적으로 손상된 사용자들은 해당 요소의 존재를 인지하지 못하고 중요한 정보나 기능을 놓칠수도 있습니다.

 

 

height, width, and overflow properties

The CSS height, width and overflow properties may be used to hide elements. For example, setting height: 0, width: 0 and overflow: hidden on an element will effectively hide it from view. Since this specifies that the element will have no visible height or width, any content that exceeds these dimensions will be hidden.

CSS의 width, height, overflow  속성은 요소를 숨기기 위해 사용할 수 있습니다. 예를 들어, 요소에 'width:0; height: 0, overflow: hidden'을 설정하면 해당요소를 시야에서 효과에서 숨길 수 있습니다. 이렇게 설정하면 해당 요소는 가시적인 높이나 너비를 가지지 않으며 이를 초과하는 모든 컨텐츠는 숨겨집니다.

Setting the overflow property to hidden ensures that any content that exceeds the element’s dimensions is not visible — instead, it is clipped or hidden from view:

overflow 속성을 hidden으로 설정함으로써 요소의 크기를 초과하는 모든 컨텐츠는 보여지지 않고 대신 클리핑 되거나 시야로 부터 숨겨집니다.

.hide-element{
  width:0;
  height:0;
  overflow:hidden;
}
N.B., it’s important to keep in mind that other CSS properties such as padding, borders, and margins can still affect the layout and positioning of the element.

참고: padding, border, margin과 같은 다른 CSS 속성들은 여전히 요소의 레이아웃과 위치에 영향을 미칠 수 있습니다.

When the height and width of a parent element is set to 0 and its overflow is set to hidden, its child elements will also be hidden and will take up no space on the page. This is because the child elements are contained within the parent element.

부모요소의 높이와 너비가 0, overflow가 hidden으로 설정되어 있으면, 해당 부모요소의 자식요소들도 숨겨지 페이지에서 공간을 차지하지 않습니다. 이는 자식요소들이 부모요소에 포함되어 있기 때문입니다.

Animatable

An element that is hidden because its height and width are set to 0, can still be animated. By gradually changing the values from 0 to our desired width and height, the element will gradually increase in size and become visible. Then, by decreasing the values back to 0, the element will gradually shrink and become hidden.

높이와 너비가 0으로 설정되어 숨겨진 요소는 여전히 애니메이션될 수 있습니다. 높이와 너비값이 0에서 원하는 값으로 점차 변경하면서, 요소는 서서히 크기가 증가하여 나타나게 됩니다. 그리고 나서 값을 다시 0으로 감소시키면, 요소는 서서히 축소되어 사라지게 됩니다.

Trigger events

Events cannot be triggered on elements hidden using the height, width, and overflow approach.

이벤트는 height, width, overflow를 사용해 숨겨진 요소에 발생할 수 없습니다. 

Performance

Using height, width, and overflow to hide elements can negatively impact the performance of the webpage, particularly if there is complex or computationally expensive content inside the hidden elements.

요소를 숨기기 위해 height, width, overflow를 사용하는 것은 웹 페이지의 성능에 부정적인 영향을 미칠 수 있습니다. 특히 숨겨진 요소 내부에 복잡하거나 계산 비용이 많이 드는 콘텐츠가 있는 경우 더 그렇습니다.

Accessibility

When elements are hidden using the height, width, and overflow approach, their content can still be read by screen readers.

요소가 height, width, overflow를 사용해 숨겨지면, 스크린 리더는 여전히 해당 요소의 컨텐츠를 읽을 수 있습니다.

 

 

transform property

The CSS transform property has multiple functions, including moving, scaling, rotating, or skewing an element. An element can be hidden using the transform property by either scaling it to 0 or translating it off-screen using values such as -999px for the horizontal axis and 0px for the vertical axis:

CSS transform 속성에는 이동, 크기 조절, 회전, 왜곡 등 여러 기능이 있습니다. transform 속성을 scale을 0으로 설정하거나, 가로축을 -999px으로 세로축을 0px로 설정해 화면 밖으로 이동시켜 요소를 숨길 수 있습니다. 

.hide-element{
  transform: scale(0);

  // or

  transform: translate(-999px, 0);
}

Hiding an element using the transform: scale() property is similar to the height and width approach. The difference is that the transform property is not affected by the element’s border, padding, or margin, so the element will completely disappear from the screen.

transform: scale() 속성을 사용해 요소를 숨기는 것은 height와 width를 사용하는 방식과 유사합니다. 차이점은 transform 속성이 요소의 border, padding, margin에 영향을 받지 않으므로, 요소는 완전히 화면에서 사라진다는 점입니다.

transform: translate(), on the other hand, can be used to move an element along both the horizontal and vertical axes. By using negative values with the translate() function, we can move an element outside its container — effectively hiding it from view. We can achieve similar results with the position property (described later in this article).

반면에 transform: translate()는 요소를 가로축과 세로축을 따라 이동시키는데 사용될 수 있습니다. translate() 함수에 음수값을 사용해서, 요소를 컨테이너 밖으로 이동시켜 화면에서 효과적으로 숨길 수 있습니다. position 속성을 사용하면 유사한 결과를 얻을 수있습니다. 

It’s worth noting that this technique hides the element, it doesn’t actually remove it from the page or change its position in the layout.

이 기술은 요소는 숨기지만, 실제로 해당 요소를 페이지에서 제거하거나 레이아웃에서 위치를 변경하지 않는다는 점을 강조해야 합니다.

In the below example, we hide a div element using the transform property:

아래 예시에서, transform 속성을 사용해 div 요소를 숨깁니다.

 

Animatable

An element that is hidden using the transform property may be animated. The transform property provides high performance and hardware acceleration as it allows the element to be moved into a distinct layer that can be animated in both 2D and 3D. This approach does not affect the original layout space.

transform 속성을 사용해 숨겨진 요소는 애니메이션화 될 수 있습니다. transform 속성은 높은 성능과 하드웨어 가속 제공하며, 요소를 2D와 3D에서 애니메이션화 될 수 있는 특정 레이어로 이동시킴으로써 이러한 성능을 얻을 수 있습니다. 이러한 접근은 원래의 레이아웃 영역에 영향을 미치지 않습니다.

We can use CSS transitions or animations to create smooth and gradual changes in the scale of an element, making it appear to fade-out or “disappear” or making it appear to slide-in from somewhere off the webpage.

요소 크기가 매끄럽고 점진적으로 변경되도록 하기 위해 CSS transition와 animation을 사용할 수 있습니다. 이를 통해 요소가 페이드 아웃 되거나 사라지게 보이거나 웹 페이지의 어딘가에서 슬라이드인 하는 것 처럼 보이게 할 수 있습니다. 

Trigger events

Events cannot be triggered on elements hidden using the transform approach.

이벤트는 transform 방식을 사용해 숨겨진 요소에서 발생할 수 없습니다. 

Performance

Using transform: scale() or transform: translate() to hide elements does negatively impact performance to a small degree, but this can be improved in some cases with the use of hardware acceleration.

요소를 숨기기 위해 transform: scale()이나 transform: translate()를 사용하는 것은 성능에 약간의 부정적인 영향을 미칠 수 있지만, 이는 하드웨어 가속화를 사용하는 몇몇 경우에서 향상될 수 있습니다.

Accessibility

When elements are hidden using the transform property, their content can still be read by screen readers.

요소가 transform 속성으로 숨겨지면, 스크린 리더는 해당 요소의 컨텐츠를 읽을 수 있습니다.

 

 

position property

The CSS position property may be used to shift an element’s default position in a webpage layout using top, bottom, left, and right values. For example, an element that is positioned absolutely can be moved off the screen by specifying a value such as left: -9999px:

CSS position 속성은 top, bottom, left, right 값을 사용해 웹 페이지 레이아웃의 기본 위치에서 이동시키기 위해 사용할 수 있습니다. 예를 들어, absolute로 위치된 요소는 left: -9999px과 같은 값으로 화면 밖으로 이동될 수 있습니다. 

.hide-element{
  position: absolute;
  left: -9999px;
}

In the below example, we hide a div element using the position property:

아래 예시에서, position  속성을 사용해 div 요소를 숨깁니다. 

 

Animatable

An element that is hidden using the position property may be animated. We can transition or animate its top, left, right and bottom property values.

position 속성으로 숨겨진 요소는 애니메이션화 될 수 있습니다. 요소의 top, left, right, bottom 속성값으로 전환하거나 애니메이션화할 수 있습니다.

Trigger events

Events could technically be triggered on an element hidden using the position approach, but this is not feasible to do when the element’s position has been shifted completely off-screen.

기술적으로 position 속성을 사용해 숨겨진 요소에 이벤트가 발생할 수 있지만, 요소의 위치가 완전히 화면 밖으로 이동된 경우에는 실행하는 것이 불가능합니다.

Performance

Using position to hide elements can impact the performance of a webpage. Even if an element has been shifted off-screen, the browser still needs to calculate the layout and space for that element, causing unnecessary rendering and layout calculations. If a large number of webpage elements are hidden in this way, it can slow down page load times and make the page less responsive.

요소를 숨기기 위해 position 을 사용하는 것은 웹페이지 성능에 영향을 미칠 수 있습니다. 요소가 화면 밖으로 벗어났을지라도, 브라우저는 여전히 요소의 레이아웃과 영역을 계산해야하므로 이는 불필요한 렌더링과 레이아웃 계산을 야기합니다. 만약 많은 웹페이지 요소가 이러한 방식으로 숨겨진다면, 이는 페이지 로드시간이 지연되고 페이지 반응성이 저하될 수 있습니다.

Accessibility

When elements are hidden using the position property, their content can still be read by screen readers even when they have been shifted off-screen.

요소가 position 속성을 사용해 숨겨지면, 요소가 화면 밖에 있더라도 스크린 리더는 여전히 요소의 컨텐츠를 읽을 수 있습니다.

 

 

Conclusion

CSS provides a wide range of techniques for hiding elements on a webpage. In this article, we explored six CSS alternatives to the traditional display: none approach. While display: none is still a valid approach to hiding content permanently, using transform or opacity may be a better choice in terms of performance.

CSS는 웹 페이지에서 요소를 숨기는 다양한 기술을 제공합니다. 이 글에서, 오랫동안 사용되는 display: none 접근 방식의 6가지 CSS 대안들을 살펴보았습니다. 여전히 display: none이 영구적으로 컨텐츠를 숨기는데 유효한 방법이지만, transform, opacity를 사용하는 것은 성능에 있어서 더 나은 선택이 될 수 있습니다.

It can be tempting to use these techniques to create interactive features or remove unnecessary content, but it’s always important to consider the impact on the user experience and accessibility. By following best practices and testing your code thoroughly, you can ensure that your website is both functional and user-friendly. I hope the techniques and tips shared in this guide will help you make the most of the powerful capabilities offered by CSS for hiding elements on your website.

상호작용적인 기능을 만들거나 불필요한 컨텐츠를 제거하는데 이러한 기술을 사용하는 것이 유혹적일 수 있지만, 항상 사용자 경험과 접근성에 미치는 영향을 고려하는 것은 중요합니다. 최상의 관행을 따르고 당신의 코드를 철저하게 테스트함으로써 웹사이트가 기능적이고 사용자 친화적인지를 보증할 수 있습니다. 이 글에서 공유된 기술과 팁이 웹 페이지에서 요소를 숨기기 위해 CSS가 제공하는 강력한 기능을 최대한 활용할 수 있길 바랍니다. 

 

  layout effect animation event handling performance accessibility
display x x x layout thrashing 또는 렌더링 지연 야기 x
visibility x o o 컴포넌트가 간단한 경우 Good
o: 비 시각장애인에게 문제가 될 수 있음
opacity/filter x o o 무시할 정도의 영향
o: 적절한 라벨링과 키보드 네비게이션 접근이 필요
clip-path o o o animation 속성값을 가지는 경우 poor
o: 적절한 라벨링과 묘사되어야 함
height
/width
/overflow
x o x 요소 내부에 복잡하거나 계산 비용이 많이 드는 컨텐츠가 있는 경우 poor o
transform o o x 영향은 있지만 하드웨어 가속화로 향상 가능 o
position o o o: 실행할 수는 있지만 요소가 보이지 않으므로 실행은 불가 Poor o

 

 

 

reference)

 

Guide to hiding elements in CSS - LogRocket Blog

We explore a variety of approaches for hiding webpage elements using CSS and evaluate them for performance and accessibility.

blog.logrocket.com

반응형

관련글 더보기

댓글 영역