- 10 Ways to Hide Elements in CSS
- Accessibility
- Event Handling
- Performance
- 1. opacity and filter: opacity()
- 2. color Alpha Transparency
- 3. transform
- 4. clip-path
- 5. visibility
- 6. display
- 7. HTML hidden attribute
- 8. Absolute position
- 9. Overlay Another Element
- 10. Reduce Dimensions
- Hidden Choices
- Share This Article
- Скрыть содержимое родительского элемента без скрытия дочерних элементов в CSS
- 2 ответы
- Revealing hidden elements when hovering a parent with Tailwind CSS
10 Ways to Hide Elements in CSS
Some CSS hiding options are all or nothing. The element is either fully visible or fully invisible and there’s no in-between state. Others, such as transparency, can have a range of values, so interpolated CSS animations become possible.
Accessibility
Each method described below will visually hide an element, but it may or may not hide the content from assistive technologies. For example, a screen reader could still announce tiny transparent text. Further CSS properties or ARIA attributes such as aria-hidden=»true» may be necessary to describe the appropriate action.
Be wary that animations can also cause disorientation, migraines, seizures, or other physical discomfort for some people. Consider using a prefers-reduced-motion media query to switch off animations when specified in user preferences.
Event Handling
Hiding will either stop events being triggered on that element or have no effect — that is, the element is not visible but can still be clicked or receive other user interactions.
Performance
After a browser loads and parses the HTML DOM and CSS object model, the page is rendered in three stages:
- Layout: generate the geometry and position of each element
- Paint: draw out the pixels for each element
- Composition: position element layers in the appropriate order
An effect which only causes composition changes is noticeably smoother than those affecting layout. In some cases, the browser can also use hardware acceleration.
1. opacity and filter: opacity()
The opacity: N and filter: opacity(N) properties can be passed a number between 0 and 1, or a percentage between 0% and 100% denoting fully transparent and fully opaque accordingly.
There’s little practical difference between the two in modern browsers, although filter should be used if multiple effects are applied at the same time (blur, contrast, grayscale etc.)
Opacity can be animated and offers great performance, but be wary that a fully transparent element remains on the page and can trigger events.
metric | effect |
---|---|
browser support | good, but IE only supports opacity 0 to 1 |
accessibility | content not read if 0 or 0% is set |
layout affected? | no |
rendering required | composition |
performance | best, can use hardware acceleration |
animation frames possible? | yes |
events triggered when hidden? | yes |
2. color Alpha Transparency
opacity affects the whole element, but it’s also possible to set the color , background-color , and border-color properties separately. Applying a zero alpha channel using rgba(0,0,0,0) or similar renders an item fully transparent:
Each property can be animated separately to create interesting effects. Note that transparency can’t be applied to elements with image backgrounds unless they’re generated using linear-gradient or similar.
The alpha channel can be set with:
- transparent : fully transparent (in-between animations are not possible)
- rgba(r, g, b, a) : red, green, blue, and alpha
- hsla(h, s, l, a) : hue, saturation, lightness, and alpha
- #RRGGBBAA and #RGBA
3. transform
The transform property can be used to translate (move), scale, rotate, or skew an element. A scale(0) or translate(-999px, 0px) off-screen will hide the element:
transform offers excellent performance and hardware acceleration because the element is effectively moved into a separate layer and can be animated in 2D or 3D. The original layout space remains as is, but no events will be triggered by a fully hidden element.
metric | effect |
---|---|
browser support | good |
accessibility | content still read |
layout affected? | no — the original dimensions remain |
rendering required | composition |
performance | best, can use hardware acceleration |
animation frames possible? | yes |
events triggered when hidden? | no |
4. clip-path
The clip-path property creates a clipping region that determines which parts of an element are visible. Using a value such as clip-path: circle(0); will completely hide the element.
clip-path offers scope for interesting animations, although it should only be relied on in modern browsers.
metric | effect |
---|---|
browser support | modern browsers only |
accessibility | content still read by some applications |
layout affected? | no — the original dimensions remain |
rendering required | paint |
performance | reasonable |
animation frames possible? | yes, in modern browsers |
events triggered when hidden? | no |
5. visibility
The visibility property can be set to visible or hidden to show and hide an element:
The space used by the element remains in place unless a collapse value is used.
metric | effect |
---|---|
browser support | excellent |
accessibility | content not read |
layout affected? | no, unless collapse is used |
rendering required | composition, unless collapse is used |
performance | good |
animation frames possible? | no |
events triggered when hidden? | no |
6. display
display is probably the most-used element-hiding method. A value of none effectively removes the element as if it never existed in the DOM.
However, it’s possibly the worst CSS property to use in the majority of cases. It can’t be animated and will trigger a page layout unless the element is moved out of the document flow using position: absolute or the new contain property is adopted.
display is also overloaded, with options such as block , inline , table , flexbox , grid and more. Resetting back to the correct value after display: none; can be problematic (although unset may help).
metric | effect |
---|---|
browser support | excellent |
accessibility | content not read |
layout affected? | yes |
rendering required | layout |
performance | poor |
animation frames possible? | no |
events triggered when hidden? | no |
7. HTML hidden attribute
The HTML hidden attribute can be added to any element:
p hidden> Hidden content p>
to apply the browser’s default style:
This has the same benefits and flaws as display: none , although it could be useful when using a content management system that doesn’t permit style changes.
8. Absolute position
The position property allows an element to be moved from its default static position within the page layout using top , bottom , left , and right . An absolute -positioned element can therefore be moved off-screen with left: -999px or similar:
metric | effect |
---|---|
browser support | excellent, unless using position: sticky |
accessibility | content still read |
layout affected? | yes, if positioning is changed |
rendering required | depends |
performance | reasonable if careful |
animation frames possible? | yes, on top , bottom , left , and right |
events triggered when hidden? | yes, but it may be impossible to interact with an off-screen element |
9. Overlay Another Element
An element can be visually hidden by positioning another over the top which has the same color as the background. In this example, an ::after pseudo-element is overlaid, although any child element could be used:
While technically possible, this option required more code than other options.
metric | effect |
---|---|
browser support | excellent |
accessibility | content still read |
layout affected? | no, if absolutely positioned |
rendering required | paint |
performance | reasonable if careful |
animation frames possible? | yes |
events triggered when hidden? | yes, when a pseudo or child element is overlaid |
10. Reduce Dimensions
An element can be hidden by minimizing its dimensions using width , height , padding , border-width and/or font-size . It may also be necessary to apply overflow: hidden; to ensure content doesn’t spill out.
Interesting animated effects are possible, but performance is noticeably better with transform .
metric | effect |
---|---|
browser support | excellent |
accessibility | content still read |
layout affected? | yes |
rendering required | layout |
performance | poor |
animation frames possible? | yes |
events triggered when hidden? | no |
Hidden Choices
display: none has been the favorite solution to hide elements for many years, but it’s been superseded by more flexible, animatable options. It’s still valid, but perhaps only when you want to permanently hide content from all users. transform or opacity are better choices when considering performance.
Take your CSS skills to the next level with CSS Master. Learn CSS architecture, debugging, custom properties, advanced layout and animation techniques, how to use CSS with SVG, and more.
Share This Article
Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he’s been advocating standards, accessibility, and best-practice HTML5 techniques. He’s created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He’s written more than 1,000 articles for SitePoint and you can find him @craigbuckler.
Скрыть содержимое родительского элемента без скрытия дочерних элементов в CSS
Таким образом, решение будет похоже на установку display:none на элемент, окружающий только строку «Hello world». Проблема в том, что нет такого и я не могу его создать.
2 ответы
display:none; всегда скрывает дочерние элементы и переопределяет их display свойства.
Вы можете попробовать использовать visibility вместо:
Кажется, это действительно работает, хотя, на мой взгляд, это совершенно неожиданное поведение — Рейндер Вит
Это не может работать, потому что элемент a все еще находится внутри родительского элемента, который не отображается. Видимость сохраняет открытым только используемое место скрытого элемента. — Свен Бидер
@Sven Bieder: это работает: jsfiddle.net/AJKeM хотя часть «Hello World» по-прежнему занимает некоторое место (проверено в Chrome и Firefox). Но, как я уже сказал, это совершенно неожиданное поведение. Рейндер Вит
Да, вам нужно сместить контейнер, если вы не хотите пустого места. У меня работает в FF, Chrome и IE9 jsfiddle.net/jfrej/n5uya — jfrej
@jfrej: под смещением вы имеете в виду какое-то абсолютное смещение? Или есть лучший подход, который работает независимо от ширины содержимого диапазона? Ваш ответ великолепен, только сейчас нужно избавиться от пустого места. — п.месоттен
Это невозможно. Это похоже на то, что у вас в руке флаг, и вы ожидаете, что, когда вы сидите в закрытой коробке, кто-то все еще может увидеть флаг в вашей руке. Единственный способ достичь этой цели — отобрать потомков от родителя и присоединить их к чему-то другому. И это будет манипулирование домом (javascript).
РЕДАКТИРОВАТЬ: после более глубоких исследований технического определения свойства видимости и желаемого поведения я понял, что этот ответ неверен. jfrej дал правильный ответ.
+1 за аналогию с закрытым ящиком. Чтобы ваша аналогия выдержала принятый ответ, вы можете считать поле прозрачным, а не исчезнувшим, когда для видимости установлено значение скрыто (вместо того, чтобы поле полностью исчезло, когда для отображения установлено значение none). — п.месоттен
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками css or задайте свой вопрос.
Revealing hidden elements when hovering a parent with Tailwind CSS
This article was written for Tailwind 2.0. As of 3.0 variants are available by default thanks to the new JIT engine. Please refer to the Tailwind 3.0 docs for further inquiry. However, group should still be the solution to this particular CSS issue. Tailwind CSS makes it almost too easy these days. Add two classes: text-blue-500 hover:text-blue-700 and you have a perfectly styled link. But what if you want to hide elements until the user hovers the mouse over a parent element? That type of UI requirement is fairly common for dashboard tables when you want to provide quick access to things without overwhelming the user with a lot of visual clutter. Tailwind is capable of doing that with group hover. For this example, we’re going to reach for a lesser used css attribute: visibility . The difference between visibility: hidden; and display: none; is the browser treats elements with their visibility set to hidden as still being present, but simply. invisible. Their space and padding are still respected, though, as if they were still present. Elements with their display set to none are essentially ignored from the markup. None of their spacing or padding impacts the page until they are visible again. We don’t want elements jumping around when the user hovers over our element, so we’ll be using visibility: hidden instead of display: none; for this example. Consider the following HTML:
class="group"> Some content that is always visible. class="invisible group-hover:visible">I am hidden until my parent is hovered!
You would probably expect this to work — but it won’t. That’s because Tailwind’s group-hover doesn’t support display types out of the box. But, with one line of code, we can easily make it work! You can add this to your tailwind.config.js file:
. variants: extend: visibility: ["group-hover"], >, >, .
Now, it will work! One thing to note: the visibility attribute cannot have transitions applied to it since it is an «on» or «off» field. If transitions is something you’re after, consider using Tailwind’s opacity.