visibility

visibility

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

Синтаксис

visibility: visible | hidden | collapse | inherit

Значения

visible Отображает элемент как видимый. hidden Элемент становится невидимым или правильней сказать, полностью прозрачным, поскольку он продолжает участвовать в форматировании страницы. collapse Если это значение применяется не к строкам или колонкам таблицы, то результат его использования будет таким же, как hidden . В случае использования collapse для содержимого ячеек таблиц, то они реагируют, словно к ним было добавлено display: none . Иными словами, заданные строки и колонки убираются, а таблица перестраивается по новой. Это значение не поддерживается браузером Internet Explorer. inherit Наследует значение родителя.

HTML5 CSS2.1 IE Cr Op Sa Fx

     .descr < visibility: hidden; >.b:hover + .descr    

Объектная модель

[window.]document.getElementById(» elementID «).style.visibility

Браузеры

Internet Explorer до версии 7.0 включительно не поддерживает значение inherit и collapse .

Браузер Safari до версии 4.0 не поддерживает значение collapse .

Opera до версии 9.5 воспринимает значение collapse как hidden для всех элементов.

Источник

hidden

The hidden global attribute is an enumerated attribute indicating that the browser should not render the contents of the element. For example, it can be used to hide elements of the page that can’t be used until the login process has been completed.

Try it

Description

The hidden attribute is used to indicate that the content of an element should not be presented to the user. This attribute can take any one of the following values:

There are two states associated with the hidden attribute: the hidden state and the hidden until found state.

  • An empty string, or the keyword hidden , set the element to the hidden state. Additionally, invalid values set the element to the hidden state.
  • The keyword until-found sets the element to the hidden until found state.

Thus, all the following set the element to the hidden state:

span hidden>I'm hiddenspan> span hidden="hidden">I'm also hiddenspan> span hidden="something else">I'm hidden too!span> 

The following sets the element to the hidden until found state:

span hidden="until-found">I'm hidden until foundspan> 

The hidden attribute must not be used to hide content just from one presentation. If something is marked hidden, it is hidden from all presentations, including, for instance, screen readers.

Hidden elements shouldn’t be linked from non-hidden elements. For example, it would be incorrect to use the href attribute to link to a section marked with the hidden attribute. If the content is not applicable or relevant, then there is no reason to link to it.

It would be fine, however, to use the ARIA aria-describedby attribute to refer to descriptions that are themselves hidden. While hiding the descriptions implies that they are not useful on their own, they could be written in such a way that they are useful in the specific context of being referenced from the element that they describe.

Similarly, a canvas element with the hidden attribute could be used by a scripted graphics engine as an off-screen buffer, and a form control could refer to a hidden form element using its form attribute.

Elements that are descendants of a hidden element are still active, which means that script elements can still execute and form elements can still submit.

The hidden state

The hidden state indicates that the element is not currently relevant to the page, or that it is being used to declare content for reuse by other parts of the page and should not be directly presented to the user. The browser will not render elements that are in the hidden state.

Web browsers may implement the hidden state using display: none , in which case the element will not participate in page layout. This also means that changing the value of the CSS display property on an element in the hidden state will override the state. For instance, elements styled display: block will be displayed despite the hidden attribute’s presence.

The hidden until found state

In the hidden until found state, the element is hidden but its content will be accessible to the browser’s «find in page» feature or to fragment navigation. When these features cause a scroll to an element in a hidden until found subtree, the browser will:

  • fire a beforematch event on the hidden element
  • remove the hidden attribute from the element
  • scroll to the element

This enables a developer to collapse a section of content, but make it searchable and accessible via fragment navigation.

Note that browsers typically implement hidden until found using content-visibility: hidden . This means that unlike elements in the hidden state, elements in the hidden until found state will have generated boxes, meaning that:

  • the element will participate in page layout
  • margin, borders, padding, and background for the element will be rendered.

Also, the element needs to be affected by layout containment in order to be revealed. This means that if the element in the hidden until found state has a display value of none , contents , or inline , then the element will not be revealed by find in page or fragment navigation.

Examples

Using until-found

The hidden until found element has a dotted red border and a gray background.

We also have some JavaScript that listens for the beforematch event firing on the hidden until found element. The event handler changes the text content of the box.

HTML

a href="#until-found-box">Go to hidden contenta> div>I'm not hiddendiv> div id="until-found-box" hidden="until-found">Hidden until founddiv> div>I'm not hiddendiv> 
button id="reset">Resetbutton> 

CSS

div  height: 40px; width: 300px; border: 5px dashed black; margin: 1rem 0; padding: 1rem; font-size: 2rem; > div#until-found-box  color: red; border: 5px dotted red; background-color: lightgray; > 
#until-found-box  scroll-margin-top: 200px; > 

JavaScript

const untilFound = document.querySelector("#until-found-box"); untilFound.addEventListener( "beforematch", () => (untilFound.textContent = "I've been revealed!"), ); 
.querySelector("#reset").addEventListener("click", () =>  document.location.hash = ""; document.location.reload(); >); 

Result

Note that although the content of the element is hidden, the element still has a generated box, occupying space in the layout and with background and borders rendered.

Clicking the «Go to hidden content» button navigates to the hidden until found element. The beforematch event fires, the text content is updated, and the element content is displayed.

To run the example again, click «Reset».

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jul 17, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Атрибут hidden

Скрывает содержимое элемента от просмотра. Такой элемент не отображается на странице, но доступен через скрипты (см. пример).

Синтаксис

Значения

В качестве значения можно указать hidden (hidden=»hidden») или оставить атрибут пустым (hidden=»» или hidden).

Значение по умолчанию

По умолчанию атрибут выключен.

Применяется к тегам

Пример

HTML5 IE 9 IE 10+ Cr Op Sa Fx

     #link function showForm() 

Авторизация на сайте

Логин:

Пароль:

Не выкладывайте свой код напрямую в комментариях, он отображается некорректно. Воспользуйтесь сервисом cssdeck.com или jsfiddle.net, сохраните код и в комментариях дайте на него ссылку. Так и результат сразу увидят.

Типы тегов

HTML5

Блочные элементы

Строчные элементы

Универсальные элементы

Нестандартные теги

Осуждаемые теги

Видео

Документ

Звук

Изображения

Объекты

Скрипты

Списки

Ссылки

Таблицы

Текст

Форматирование

Формы

Фреймы

Источник

Как прятать

Зависит от того, что вы пытаетесь сделать. Есть и другие варианты как спрятать блок и даже специальный атрибут.

Если вам приходится что-то прятать, то лучше всего это вообще убрать: сайт легче, код чище… ошибок меньше! Но если вам нужно, чтобы оно там пряталось до поры, а потом кому-то пригодилось — это другое дело. Здесь важно не ошибиться с выбором способа.

Самый простой и популярный — display: none, он работает как топор: элемент как будто вырубают из HTML. Его не видно на странице и соседние блоки про него ничего не знают. Просто нет и всё. Его даже скринридеры игоририруют и не читают содержимое — будьте аккуратнее с этим.

Что интересно, несмотря на полное вырубание элемента, браузеры всё равно загружают картинку из img с display: none. Если же картинка указана фоном, то Chrome и Edge её тоже загружают, а Firefox и Safari — нет. Ну, разные у них взгляды на оптимизацию загрузки, что поделать.

Другой способ — visibility: hidden, он работает как кольцо всевластья: элемент вроде здесь и соседние блоки его чувствуют, но его не видно. И чем это отличается от opacity: 0? Opacity просто делает элемент прозрачным (или полупрозрачным), а visibility: hidden ещё не даёт с ним взаимодействовать: навести, кликнуть, сфокусировать.

/* Прячет */ .one-ring < visibility: hidden; >/* Не сработает */ .one-ring:hover

У visibility: hidden есть другая приятная особенность: свойство наследуется, а значит ребёнок невидимого родителя может сменить видимость на visible. Такой трюк не пройдёт ни с display: none, ни с opacity: 0. С ним удобно делать всплывающие меню и подказки.

Иногда нужно, чтобы элемент не мешал дизайну, но при этом не прятался от скринридеров, оставаясь частью содержимого. Ну не нарисовал дизайнер здесь заголовка, а по логике документа он здесь нужен. Вот бы нам что-то вроде display: hidden или visibility: none! Это я только что придумал, в природе их не существует.

Недавно в черновике CSS Display третьего уровня появилось свойство box-suppress со значениями show, discard и hide. Оно отвязывает видимость блока от display — ведь с обратной стороны от none есть не только block, но и inline, flex, grid. Значение discard привычно вырубает элемент, а hide делает то самое волшебное комбо. Читайте подробнее у Рейчел Эндрю.

К сожалению, до box-suppress нам ещё долго ждать. Его не только ещё нет в браузерах, но уже в том черновике — недавно его перенесли в следующий уровень, чтобы закончить текущий вовремя. Так что придётся делать магию самим — следите за руками.

Есть такой паттерн «visually hidden» или «визуально спрятанный», чтобы прятать элементы из дизайна, но оставлять доступным их содержимое. Про другие нюансы со скринридерами читайте у Тима Райта. Как это работает: вы делаете универсальный служебный класс и добавляете его к элементам, которые нужно доступно спрятать. Обычно его так и называют: visually-hidden, через дефис.

 

Важный за головок, которого нет

Если посмотреть что внутри, то это обычный position: absolute плюс clip, который обрезает элемент до нуля. То есть он не влияет на соседей и становится невидимым. Все остальные свойства добавляют универсальности и кроссбраузерности, чтобы класс можно было не глядя шлёпнуть на любой элемент. Подробнее читайте в справке к ally.js Родни Рейма.

А вы знали, что любому элементу можно добавить атрибут hidden и он пропадёт? Теперь знаете! В современных браузерах на этот атрибут повешен тот самый display: none, который вырубает элемент. Он бинарный как required или checked, так что его удобно выставлять через JavaScript. Только не забудьте добавить в стили [hidden] < display: none >для IE 10, Safari 5 и других старых браузеров.

  // JS div.hidden = true;

Это почти всё, что вам нужно знать про прятки в CSS. Попробуйте эти способы, они все хороши в разных ситуациях. Главное, не рубите с плеча и думайте о доступном содержимом.

Источник

Читайте также:  Enable java security warning
Оцените статью