Как скрыть элемент в html
Перейти к содержимому

Как скрыть элемент в html

  • автор:

visibility

Свойство visibility скрывает или показывает элемент без изменения разметки документа. Также скрывает строки и столбцы <table> (en-US).

Интерактивный пример

Чтобы скрыть и удалить элемент из разметки, установите свойству display значение none , вместо использования visibility .

Синтаксис

Свойство visibility указывается в качестве одного из значений ниже.

Значения

Значение по умолчанию, элемент виден.

Элемент не виден (полностью прозрачный, ничего не отображается), но продолжает влиять на шаблон. Потомки элемента могут быть показаны с помощью свойства visibility:visible . Элемент не может получить focus (например, при навигации с помощью tabindex).

* Для строк, столбцов, групп столбцов и групп строк в таблице, которые должны быть удалены (как с помощью display : none применённого к столбцу/строке таблицы). Однако, размер других строк и столбцов должен продолжать вычисляться так, словно скрытые строки/столбцы присутствуют. Это создано для быстрого удаления строк/столбцов из таблицы без дополнительного вычисления ширины и высоты частей таблицы.

  • Для XUL элементов размер всегда равен 0, независимо от других стилей, влияющих на размер, хотя отступы продолжают учитываться.
  • Для других элементов collapse обрабатывается также, как hidden

Синтаксис

Интерполяция

Значения видимости изменяются между видим и не видим. Интерполяция будет, если одно из начальных или конечных значений будет видимо или нет. Если одно из значений visible , интерполируется как дискретный шаг, где значения временной функции от 0 до 1 для visible и другие значения временной функции (которые происходят только в начале/конце перехода, или как результат функции cubic-bezier() со значениями вне [0, 1]) ближе к конечной точке.

# Hiding DOM elements

This document explains the various ways of hiding things and the implications that come with that.

When we say an element is hidden, we usually mean it is not visible. However, the screen is not the only output mechanism we may need to hide content from. Systems like screen readers and braille displays rely on a document's representation in the accessibility tree. For disambiguation we'll use the following terms:

Completely hidden The element is not rendered on screen, not exposed in the accessibility tree, not accessible to keyboard navigation. Semantically hidden The element is rendered on screen, but not exposed in the accessibility tree, and still accessible to keyboard navigation. Visually hidden The element is not rendered on screen, but exposed in the accessibility tree, and still accessible to keyboard navigation.

The three types of "hidden" produce the following matrix:

visibility state on screen in accessibility tree keyboard navigation
completely hidden hidden hidden not navigatable
semantically hidden visible hidden navigatable
visually hidden hidden visible navigatable

# How to hide elements completely

Completely hiding elements can be done in 3 ways:

  • via the CSS property display , e.g. display: none;
  • via the CSS property visibility , e.g. visibility: hidden;
  • via the HTML5 attribute hidden , e.g. <span hidden>

While each of these techniques has the same end result, i.e. content is not rendered and not exposed in the accessibility tree, they have different behaviors.

# The CSS properties display and visibility

display: none; will cause the element to completely vanish, it won't take any space and it won't be animatable. visibility: hidden; allows animation and preserves the space the element would occupy on screen, but simply leave it blank. Unlike every other method to hide content, visibility has the ability to unhide nested content:

Unless unhiding nested content is specifically what we intend to do, we should refrain from using visibility: visible; in our style sheets, and use visibility: inherit; instead. By inheriting the visibility state from the parent element by default, we make sure that nested content does not become visible by accident, in case the an ancestor has visibility: hidden; set.

# The HTML5 hidden attribute

The HTML5 hidden attribute provides a convenient API, as it can be toggled simply by setting element.hidden = true; . The element itself does not hide the content, but browser's internal style sheets contain the following CSS rule:

# Safely overwriting the hidden attribute

We absolutely must not revert the hiding effects of the hidden attribute. However, we can swap display for visibility in certain situations, for example to allow us to animate the element:

Sadly we cannot use the values inherit , initial or unset to simply undo the display: none; . initial and unset would translate to display: inline , and inherit simply "imports" the display value of the parent element. We can use extended selectors to get around duplicate definitions:

# How to hide elements semantically

To hide content from the accessibility tree but retain the content on screen, we may use the attribute aria-hidden="true" .

For example we might want to hide certain images and icons that serve non-descriptive, purely esthetical purposes:

We should not add any visual styles (like visibility: hidden; or display: none; ) to the CSS selector [aria-hidden="true"] , as this would make us lose the ability to hide content only from screen readers.

# How to hide elements visually

We may need to provide invisible content in order to make sure the structures presented in the accessibility tree make sense. The following CSS is taken from HTML5 Boilerplate, which is based on Hiding Content for Accessibility:

The CSS property clip is supported in every browser, but was deprecated in CSS Masking Level 1. Instead we're supposed to use clip-path , which isn't widely supported yet. To support this swap of CSS properties — whenever that may happen — we would add clip-path: inset(100%); to cover the deprecated clip: rect(0 0 0 0); style.

While Internet Explorer 9 — 11 make overflowing containers focusable, the clip makes sure the outline drawn by :focus is not visible and the element cannot be clicked on.

Speaking of focusable elements, we are likely using the .visuallyhidden style for skip links, in which case we need a way to undo the visual hiding. The HTML5 Boilerplate provides the following styles for that:

This approach poses a couple of problems, though. First of all we need to declare elements compatible by adding the class focusable . Second — and much more importantly — we're resetting styles to values that are likely not what we intend to render. Instead we could use :not() , which is supported in every modern browser.

According to Beware smushed off-screen accessible text the above snippet of CSS might pose a problem to some screen readers. It seems that (in some situations) separate words might be concatenated and thus spoken weirdly. Luckily we can prevent the undesired collapse of whitespace by adding white-space: nowrap; .

# 2017 edition of .visuallyhidden

Putting all of this together we get the following styles to visually hide content:

  • It works in all modern browsers including Internet Explorer 9 — 11.
  • It side-steps the need to re-style everything for focusable elements such as skip-links.
  • It accounts for the deprecated clip property.

# Keyboard navigation

The techniques to hide elements only visually or semantically come with a caveat. Focusable elements like <a href="…"> remain keyboard navigatable, even though the element is not visible on screen or not exposed in the accessibility tree.

To make sure sighted keyboard users do not end up focusing elements they can't see, and screen reader users not focusing element's that don't exist for them, we need to make sure that partially hidden content is not accessible to keyboard navigation using the Tab and Shift Tab keys. To accomplish this, we can add tabindex="-1" to the elements we want to hide from the keyboard.

Element Hiding Techniques in CSS

This difference is to hide an element and its content entirely or hide an element but show its content to the screen readers. We know that hiding something is not just cosmetic, but for a lot of us, it is accessibility. We can create things which goal is to be invisible to the eye but visible for the readers.

Of course, there are other areas where we want to know the differences between the hiding techniques, for example in the case of animation. Animating the display property is not possible, so we should use the opacity, but doing this the hidden content stay actionable – if there clickable element, we can interact, or we can’t click through it – so we want to find a solution which usually is the visibility property.

These are some examples from the life of the everyday front-end developer, and I think – as usual – that this is interesting. I infrequently think about how many times I’m hiding elements just from CSS and being honest I rarely use them consciously. I just learned in the years what to use in which situation. I’m sure that every intermediate CSS dev will do and think similarly.

Bazar is a powerful «headless» e-commerce system. Built on Laravel and Vue.

Generally, there is three property which purpose – in some way – is hiding an element: the display , the visibility , and the opacity . You can hide in another way too, but for that, you need more than one property. We talk about the other techniques in the last section! Let’s start the explore!

Hide Elements with The Display Property

Setting the display property to none value will cause the true hidden state in your document. Your content will be still present in your HTML, but the box-model isn’t generated, your elements don’t reserve any space. You also can’t interact with the components. You can select the elements through JavaScript but can’t get its width or height.

If you use display: none; all of the descendant elements will be invisible too, and you can’t switch them back declare them as block – or any “visible” value – display. You can’t animate these parts in any way (with CSS). The content will be invisible for screen readers too.

As you see in the example – by clicking the toggle button – when the element is hidden it disappears from the flow.

Has box model? Accessible for screen readers? Actionable?
display: none; No No No

Hiding Elements with The Visibility Property

The visibility: hidden; declaration is between the display and the opacity property. Using the visibility property the element has the box-model, so it takes its place in the layout, but we can’t interact with the component from the user side.

The elements hidden with this property will be invisible for the screen readers but remain animated.

For me, this method is useful when I’m designing a drop-down – in this case, a basic one – menu. In case of a dropdown, we use absolute positioning, so the box-model is not a problem because we get the item out from the document flow. Combining with opacity, we can animate it and also disable the interaction when the dropdown is invisible.

If you toggle the visibility, you can open the dropdown when you navigate to the position where it will appear; this is because only with opacity the element is actionable but after set visibility: hidden; it disappears.

Has box model? Accessible for screen readers? Actionable?
visibility: hidden; Yes No No

Hiding Elements with Opacity

Using the opacity property, we can hide our elements just visually; this means it has its box-model and remains actionable. This property can get a value between 0 and 1, defining it we set an element’s and its children’s transparency.

Because it is just visually hiding the content will be accessible for screen readers, and we can animate it too.

By alone this can be useful when we design some article/blog card where the content is revealed on hover – and it is not a problem that it is actionable because we show it on hover event – as you see in the next example:

If you inspect this pen, you can see that the .sh-effect–delta__overlay have had a zero transparency.

Has box model? Accessible for screen readers? Actionable?
opacity: 0; Yes Yes Yes

Hiding Elements but Show Them to The Screen Readers

As I said earlier the hiding is starting to be interesting when you want to hide something but show it to the screen readers. For the accessible design, this is more than necessary. As you know now you can’t do it with the previous – one-line solutions – we need other solution which is hacks.

Hiding Elements with Position

Hiding elements using the position property is simple, we set a high negative top and/or left value. With this method, the element’s content is still accessible with a screen reader, but it is “removed” from the content flow.

For example check out the classic .screen-reader-text code:

Hiding Elements with Clip-path

Using clip-path we can achieve a more modern solution for the previous a11y hiding problem. With this property, we can set zero with and height mask to our element so it will be hidden. It is supported in all modern browsers except IE and Edge, but we can declare fallbacks.

+1 Hiding with Max Height and Hidden Overflow

Hiding with max-height property is a specific use case, but it is still functional. If you want to build accordion navigation which is animated you can use max-height: 0; and overflow: hidden; .

In CSS we can’t animate elements using height – like from zero to auto – but we can animate max-height: 0; to max-height: 1000px; . In some cases, this is not the best solution because it is using fix values.

As you see the content will be hidden just by height and overflow. These content will be visible for the screen readers too.

Как скрыть элемент с помощью CSS?

Как спраятать элемент на странице

Делая верстку страниц сайта, зачастую возникает необходимость придания блокам на странице различных эффектов оформления и поведения при взаимодействии с пользователем для придания интерфейсу нашего сайта более интересного вида. Например, можно скрыть элемент css свойствами, и в нужный момент или при наведении на него курсора мышки отобразить его.

Способов скрыть элемент css свойствами достаточно много. Если поинтересоваться этим вопросом в поисковиках, то можно найти различные варианты решения этой задачи от самых простых до самых изощренных. Для начинающего веб-разработчика это может стать настоящей проблемой, так как пока вы все их перепробуете и определите для себя самые простые и рабочие из них, вы потратите на это значительное количество времени и своих драгоценных нервов.

Навигация по статье:

Я предлагаю рассмотреть четыре наиболее простых и эффективных способа скрыть элемент css, которые вы можете использовать в 99% случаях, которые на 100% рабочие и которые вас никогда не подведут.

Полное срытие элемента

Для того, что бы полностью скрыть элемент со страницы мы можем воспользоваться свойством display со значением none. Данная запись полностью скроет элемент и при формировании страницы под него не будет зарезервировано пространство. Данное свойство поддерживается абсолютно всеми браузерами.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *