This is a premium alert message you can set from Layout! Get Now!

Guide to hiding elements in CSS

0

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.

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 we’ll 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.

Jump ahead:

Tradeoffs to consider when using CSS to hide an element

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:

  • 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

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

  • 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
  • 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
  • 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

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.

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

.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.

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:

See the Pen
Display-none-example
by King nelson (@D_kingnelson)
on CodePen.

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.

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.

Performance

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

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.

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:

.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:

See the Pen
visibility-example
by King nelson (@D_kingnelson)
on CodePen.

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.

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.

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.

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.

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.

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.

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.

.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 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.

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

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

See the Pen
filter-opacity-example
by King nelson (@D_kingnelson)
on CodePen.

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.

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.

Performance

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

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.

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:

.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.

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

See the Pen
clip-path-example
by King nelson (@D_kingnelson)
on CodePen.

Animatable

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

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.

Performance

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

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.

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.

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.

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.

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:

.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

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.

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.

Trigger events

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

Performance

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

Accessibility

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

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:

.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: 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).

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:

See the Pen
transform-example
by King nelson (@D_kingnelson)
on CodePen.

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.

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.

Trigger events

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

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.

Accessibility

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

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:

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

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

See the Pen
position-property-example
by King nelson (@D_kingnelson)
on CodePen.

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.

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.

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.

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.

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 hide content permanently, using transform or opacity may be a better choice in terms of performance.

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.

The post Guide to hiding elements in CSS appeared first on LogRocket Blog.



from LogRocket Blog https://ift.tt/SWnfQNT
Gain $200 in a week
via Read more

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment

Search This Blog

To Top