Свойства css display и visibility: как скрыть элемент css или элемент html?

Алан-э-Дейл       31.03.2024 г.

Incomplete Workaround: Fade-In and -Out using Transitions on Opacity

Most often the opacity property is used instead of visibility,
which results in a fade-in and fade-out effect. The idea is that a completely
transparent element is very similar to an element with visibility:hidden.

<style >
   .cl0  { opacity : 0; transition:opacity 1s; }
   .cl0:hover { opacity : 1}
</style>
 
<div class=»cl0″>
   Sample Text
</div>

<span class=»hoverhere»>Hover over the Line Above this Line</span> <br>

fails on IE8 and still catches events while invisible

 
Sample Text

Hover over the Line Above this Line
fails on IE8 and still catches events while invisible

However care has to be taken with that approach, because unlike an invisible element (with visibility:hidden)
a fully transparent element (opacity:0) still catches events and e.g. a transparent link still
functions. The blog article CSS Transition Opacity for Fade Effects has a detailed description
and examples of that problem. Also old browsers like IE8.0 do not understand the opacity property
and so this simple approach will never hide the element in IE 8.

The solution is to combine the opcity transition with a
transition on visibility. Before we discuss that in detail
after the next the section, the next section itself explains
the detailed workings of transitions on visibility.

Show/Hide DIV with JavaScript

to toggle visibility:hidden DIV or to toggle display:none DIV

Content above visibility:hidden DIV.

This DIV was initially set to visibility:hidden.
Now you can see it!

Content below visibility:hidden DIV.

Content above display:none DIV.

Content below display:none DIV.

The JavaScript functions used in the examples above are as follows:


  function toggleDivVisibility(theDiv) {
    (document.getElementById(theDiv).style.visibility == 'visible') ? 
       document.getElementById(theDiv).style.visibility = 'hidden' :
         document.getElementById(theDiv).style.visibility = 'visible';
   }

  function toggleDivDisplay(theDiv) {
    (document.getElementById(theDiv).style.display == 'block') ? 
       document.getElementById(theDiv).style.display = 'none' :
         document.getElementById(theDiv).style.display = 'block';
   }

But we can do something a bit more elegant than simply turning a switch on or off…

Селекторы

Вместо , и универсальных селекторов (с ними всё сложно) используйте классы и селекторы классов. В случае с CSS, id-селектор будет лучше любого другого селектора, но id-селекторы должны быть уникальными на каждой странице, так что они не подходят для внедрения одних стилей сразу для нескольких элементов.

Производительность CSS-селекторов в современных браузерах — вопрос не первой важности, возможно, вы слышали об универсальном селекторе (*). О чём действительно стоит беспокоиться, так это о слишком большом охвате этого селектора

В будущем это может повлечь больше неудобств, чем пользы. Использование селектора вроде в конечном счёте потребует от вас выбрать какой-нибудь дочерний класс, так что вам придётся добавлять другие классы и направлять этот селектор на них.
Тот же самый аргумент можно привести в пользу неиспользования type-селекторов (, ), которые скапливаются в больших количествах и требуют добавления некоторых идентифицирующих свойств . Вот такие множественные селекторы более специфичны, и вероятность багов меньше.
То же самое с селекторами ,  и .

Видимость элемента в CSS

display

Возможные значения:

  • (отображается как блочный)
  • (временно удаляет элемент из документа)
  • (отображается как встроенный (строчный))
  • (внутренняя часть форматируется как блочный элемент, а сам элемент — как встроенный, обтекается другими элементами (подобно img))
  • (отображается как блочный и добавляется маркер списка)
  • (элемент в качестве таблицы, но при этом таблица является встроенным элементом и происходит ее обтекание другими элементами)
  • (элемент в качестве блочной таблицы)

Пример:

divhover{
	displaynone;
}

Результат:

Наведите курсор
А я без стиля

visibility

Возможные значения:

  • (становится невидимым, но участвует в нормальном потоке элементов)
  • (отображается как видимый)
  • (для содержимого ячеек таблиц, отображаются как будто применен стиль (заданные строки и колонки убираются))

Пример:

divhover{
	visibilityhidden;
}

Результат:

Наведите курсор
А я без стиля

overflow

Возможные значения:

  • (отображается все содержание элемента, даже за пределами установленной высоты и ширины)
  • (отображается только область внутри элемента, остальное будет обрезано)
  • (всегда добавляются полосы прокрутки)
  • (полосы прокрутки добавляются только при необходимости)

Пример:

div{
	width150px;
	height150px;
	overflowscroll;
}

Результат:

Это пример параграфа1. Это пример параграфа2. Это пример параграфа3. Это пример параграфа4. Это пример параграфа5. Это пример параграфа6. Это пример параграфа7. Это пример параграфа8. Это пример параграфа9. Это пример параграфа10. Это пример параграфа11. Это пример параграфа12. Это пример параграфа13. Это пример параграфа14. Это пример параграфа15. Это пример параграфа16. Это пример параграфа17. Это пример параграфа18.

Тот же самый пример с другим свойством:

div{
	width150px;
	height150px;
	overflowhidden;
}

Результат:

Это пример параграфа1. Это пример параграфа2. Это пример параграфа3. Это пример параграфа4. Это пример параграфа5. Это пример параграфа6. Это пример параграфа7. Это пример параграфа8. Это пример параграфа9. Это пример параграфа10. Это пример параграфа11. Это пример параграфа12. Это пример параграфа13. Это пример параграфа14. Это пример параграфа15. Это пример параграфа16. Это пример параграфа17. Это пример параграфа18.

SEO Effects of Visibility and Display

A sometimes used spam tactic is to stuff keywords on a page and make them invisible in some way. Often this is done not through either of the css properties above, but rather by giving the text the same color as the background it sits on or making the font so small as to render it invisible.

Because these tactics are frowned up by search engines, some people worry about using either the visibility or the display property to “hide” html.

There are many good reasons why you want some elements in your design to sometimes be seen and sometimes not be seen and search engines understand that. As long as you aren’t trying to trick search engines in any way you shouldn’t encounter any problems using either visibility or block to show and hide an element.

« Prev PostNext Post »

Download a free sample from my book, Design Fundamentals.

Hidden

Это значение противоположность . Оно скрывает любой контент, выходящий за рамки контейнера. Повторим первый пример, но с примененным к контейнеру свойством:

See the Pen
overflow hidden by Андрей (@adlibi)
on CodePen.

Текст, который выходит за пределы , перестал быть видимым.

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

Property Values

Value Description Demo
visible Default value. The element is visible Demo ❯
hidden The element is hidden (but still takes up space) Demo ❯
collapse Only for table rows (<tr>), row groups (<tbody>), columns (<col>),
column groups (<colgroup>). This value removes a row or column,
but it does not affect the table layout. The space taken up by the row or column
will be available for other content.

If collapse is used on other elements,
it renders as «hidden»

initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

Способ #2. alpha-канал

Свойство влияет на элемент целиком, но вы можете также изменять видимость отдельных свойств: цвета (), фона () или рамки (). Чтобы скрыть их, используйте цвет в формате rgba (или hsla) и установите значение альфа-канала равным нулю, например, .

See the Pen
hide with color alpha by SitePoint (@SitePoint)
on CodePen.

Каждое свойство можно анимировать отдельно для создания интересных эффектов.

Эту технику нельзя применить к фоновым изображения (кроме тех, которые созданы с помощью CSS-градиентов).

Способы управления альфа-каналом:

  • Ключевое слово . Устанавливает полную прозрачность, не поддерживает промежуточные анимации.
  • : красный, зеленый, синий и альфа-канал.
  • : оттенок, насыщенность, светлота и альфа-канал.
  • HEX-формат: или
Метрика Влияние
Браузерная поддержка Хорошая. В IE поддерживается только ключевое слово и rgba-формат.
Доступность скрытого элемента Контент остается доступным
Вызывает изменение макета Нет
Перерендеринг Painting
Производительность Хорошая, но медленнее, чем у
Покадровая анимация Возможна
Срабатывание событий на скрытом элементе Да

Absolute position

The property allows an element to be moved from its default position within the page layout using , , , and . An -positioned element can therefore be moved off-screen with or similar:

See the Pen
hide with position: absolute by SitePoint (@SitePoint)
on CodePen.

metric effect
browser support excellent, unless using
accessibility content still read
layout affected? yes, if positioning is changed
rendering required depends
performance reasonable if careful
animation frames possible? yes, on , , , and
events triggered when hidden? yes, but it may be impossible to interact with an off-screen element

Appear Inside — Clipping using Overflow:hidden and CSS transition on Top and Left

The idea of this workaround is to simulate hidden visibility by
using the overflow:hidden specification for the outer div
element. This specification hides the inner div while it is positioned
outside the outer one. Then the transition moves the inner div outside and inside
the outer div. It will not move across the document but vanishes as soon as it leaves
the outer div.

Main difference of the example below is the overflow:hidden specification
for the outer div element.
This means that whenever the inner div is positioned outside the outer one,
it is hidden. This is done using left : 150px; top:-150px;.
When hovering over the outer div,
the .outer3:hover > div { left : 0px; top:40% } rule applies
and the inner div moves to its normal position inside the outer div
and thereby appears.

<style >
   .cl3           { background‑color:yellow; width:80%; padding:10%;
                      position:relative; left : 150px; top:‑150px; 
                      transition‑property:all; transition‑duration:1s;}
   .outer3     { width:90%; height:150px; overflow:hidden}
   .outer3:hover > div { left:0px; top:30% }
</style>
 
<div class=»outer3″>
      <div class=»cl3″>

            Sample Text
      </div>

      Hover Here
</div>

 

Sample Text

Hover Here

Очистка Float

Как ни странно, одним из наиболее популярных способов использования является очистка свойства .

Проблема встречается в следующем: когда вы помещаете в элемент дочерний элемент с установленным свойством (плавающий), то родительский элемент не растягивается, чтобы охватить дочерний элемент, а сворачивается, не учитывая его. Это бывает проблемой, например, когда у родительского элемента задан фон или рамка.

На примере это наглядно видно. Внутри родительского элемента (в синей рамке) помещен элемент с текстом и установленным свойством . Родительский элемент при этом свернулся.

See the Pen
overflow float by Андрей (@adlibi)
on CodePen.

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

See the Pen
overflow float 2 by Андрей (@adlibi)
on CodePen.

#644 – Disabling and Hiding Controls

September 11, 2012

You can disable a control by setting its IsEnabled property to false.  Disabled controls cannot receive input, but are still displayed in the user interface, typically greyed out.

Below is an example of some typical controls, showing what they looked like when enabled vs. disabled.

In addition to disabling a control, you can also make the entire control invisible, using the Visibility property.  Controls that are not visible can be one of:

  • Hidden – Control is not visible, but it still takes up space in the user interface.  I.e. There is whitespace where the control would be if it were visible
  • Collapsed – Control is not present at all in the user interface and neighboring controls fill in the space where the control would be if it were visible

Negative Blends

Idea is to simulate hidden visibility by moving another element in
front covering the «Sample Text». The covering element gets
the background-color of the neighbor elements and so is
not realized by the viewer. There are many transition possibilities
to make the covering element appear and disappear, below we
give an example for a negative circle blend.

Note that in this example the «Sample Text» element is not contained
in the middle element, but instead both elements are contained
on the same level inside the outer element.
Using absolute and/or relative positioning both elements are
positioned on top of each other and using z-index the middle
element is put on top covering the «Sample Text» element.
Using border-radius the middle element is turned into
a circle. This circle is, however, invisible since it has
a white background color. And because it covers the «Sample Text» element
nothing is visible initially.

When you hover over the element, the middle element is resized to
zero using the transition to width:0px; height:0px;
and so the covering circle disappears and the «Sample Text» element
below appears.

<style >
   .cl9        { background‑color:yellow; width:100px; padding:10px;
                      padding‑top:30px; padding‑bottom:30px;
                      position:relative; top:32px; left:10px}
   .middle9    { border‑radius:100px; background‑color:white; 
                      z‑index:1; position:absolute; 
                      width:145px; height:145px;
                      margin‑left:0px; margin‑top:0px;
                      transition‑property:all; transition‑duration:1s;}
   .outer9     { width:90%; height:150px; overflow:hidden}
   .outer9:hover > div { width:0px; height:0px; 
                      margin‑left:67px; margin‑top:69px }
</style>
 
<div class=»outer9″>
      Hover Here
      <div class=»middle9″>

      </div>

      <p class=»cl9″>

           Sample Text
      </p>

</div>

 
Hover Here

Sample Text

The additional transition on margin-left:67px; margin-top:69px
is needed to make the circle appear closing and opening from its center point.
In other words, while the circle is shrinking it is moved down and left,
so that its center point stays fixed.

CSS Fade-in Show/Hide DIV

The conventional CSS show/hide techniques shown above act instantly and always
struck me as a bit jarring. And when a question about this appeared in the WebDeveloper.com forum,
I decided to create an example using CSS transitions. The forum message involved using a list of links that would selectably hide and reveal sections
of a document. Try clicking on the menu items and see how it works.

Content Box 1

We start with some initial text visible to the user. Additional
content is stacked invisibly within the document. Nothing
special happens until the user takes the affirmative action of clicking on a
menu item to reveal a different content section.

Content Box 2

Here is a selectable section of additional text that
can be revealed when the user clicks on the link in the list on the left.
User engagement is key to holding an audience and enticing further
exploration of your website through creative design techniques.

Content Box 3

CSS transitions add drama and style through animated effects
that provide more emotional impact and flair. The visibly changing content
attracts the eye and attention of the user more than an instant change. As
always, you want to keep such special effects limited to avoid having your
style outweigh the substance of your website content.

The JavaScript required to perform the selection function is very similar to the conventional
show/hide script shown above. The difference is that we’re relying on the CSS «opacity» property instead of
«visibility» or «display» and the content DIVs are all using position:absolute with an
appropriate z-index so they’re stacked on top of each other. In addition, the content boxes all have their
«transition» property set so CSS3-compatible browsers will show the change in display gradually. Older
browsers will simply see the change instantly.


var rdFadeBoxName = 'rdFadeBox';
var rdFadeBoxCurrent = 1;

 function rdFadeBoxSelect(rdFadeBoxNum) {
  if (rdFadeBoxNum != rdFadeBoxCurrent) {  // Only process requests to reveal new content!
   document.getElementById(rdFadeBoxName + String(rdFadeBoxCurrent)).style.opacity = '0';
   rdFadeBoxCurrent = rdFadeBoxNum;
   document.getElementById(rdFadeBoxName + String(rdFadeBoxCurrent)).style.opacity = '1';
  } // endif (rdFadeBoxNum != rdFadeBoxCurrent)
 } // end rdFadeBoxNext()

More CSS Tutorials

CSS PositioningCSS Nested DIVs & Floats TutorialCSS Effects on Element SizeCSS Visibility TutorialCSS Centering TutorialCSS Vertical Align TutorialCSS Overflow TutorialChanging Stylesheets With JavaScriptWhen To Use Class or ID in CSSMultiple Backgrounds in CSS3How CSS Affects Element SizeStyling <table>s with CSS

All of the JavaScript and CSS is embedded in this document, so you can see all of the details. You’ll
also notice that I included «Next» and «Previous» functions so you could give users
buttons to control the display instead of a menu-type list of selections. You could also change the functions to
highlight the currect menu selection.

This page was last modified on October 01, 2020

Fly In from Outside the Screen — CSS Transition on Left and Top

The idea of this approach is to move an element somewhere off the
screen and to so simulate a hidden visibility.
This works nicely and the transition shows the element
flying from outside the document to its normal position
and vice versa.

We modified the example code given above accordingly, leading to the example below.
The first thing we added was «width:80%; padding:10%; background-color:yellow;»
which gives the element a yellow background and some padding.
This is not really required but makes the example look better.
Then we gave the element a position outside of the screen using
position:relative; left : -2000px; top:-500px;, i.e. we moved the element
2000px to the left and 500px to the top from its normal position.
This effectively hides the element without actually using the visibility property.
Finally we define transition-property:all; transition-duration:1s;
to enable transitions on all properties (we could also have used just left and top).

On activation of the transition we would like move the element to its normal position
on the screen e.g. using left : 0px; top:40%. However a rule
as above like .cl2:hover { left : 0px; top:40% } will not work,
because initially the element is moved off the screen and you cannot move
the mouse there. So what we do it to put another div of class outer2
around the sample element. The outer div is normally invisible (we just gave
it a blue border for illustration). Then we can write a rule
.outer2:hover > div which means that whenever the mouse hovers
the outer element then the inner div should get the specified format,
{ left : 0px; top:40% } in the example.

<style >
   .cl2           {width:80%; padding:10%; background‑color:yellow;
                       position:relative; left : ‑2100px; top:‑500px; 
                       transition‑property:all; transition‑duration:1s;}
   .outer2     {border : 1px blue solid; width:90%; height:100px;}
   .outer2:hover > div {left:0px; top:40%}
</style>
 
<div class=»outer2″>
      <div class=»cl2″>

            Sample Text
      </div>

      Hover Here
</div>

 

Sample Text

Hover Here

You can also implement a similar transition using
another new HTML5 technique called HTML5 canvas 3D or WebGL
and the taccgl javascript library.

The example script below first finds the HTML element with id=demo.
Then from(-600,4000,0) declares the corresponding fly in transition
from coordinates (x=-600,y=4000,z=0). The vEnd(0,0,0)
gradually slows down the motion, which corresponds to the default
timing
function of the transition example.

taccgl.actor(«demo»,null,»visible») .from(-600,4000,0). vEnd(0,0,0) . start() RUN

The taccGL/WebGL example can easily be extended to display a curved surface showing a kind of page flip effect.

taccgl.actor(«demo»,taccgl.flexiBorder,»visible») .from(-600,4000,0). Flip(0,0). Rect1(). vEnd(0,0,0) . start() RUN

Also a shadow can be included.
In the example below a first line for the shadows and a z-coordinate for the
source position of the element were added:

taccgl.a(document.body).color(«white») .shadowOnly().showAfter() .start();
taccgl.actor(«demo»,null,»visible») .from(-400,2500,2000).

vEnd(0,0,0).duration(3).start()

RUN

Very similar examples are discussed in the WebGL-HTML5 PopUp Animations
article or see our WebGL webdesign homepage for more
details on taccgl.

Callbacks

Callbacks are separated into two categories. Standard events will occur the first animation frame where the conditions evaluated to true.

Standard Events

Event Occurs Pseudocode
onOnScreen Any part of element is in current scroll viewport screen.bottom >= element.top && screen.bottom
onOffScreen No part of element is in current scroll viewport screen.bottom = element.bottom
onTopVisible Element’s top edge has passed bottom of screen screen.bottom >= element.top
onTopPassed Element’s top edge has passed top of the screen screen.top >= element.top
onBottomVisible Element’s bottom edge has passed bottom of screen screen.bottom >= element.top
onPassing Any part of an element is visible on screen screen.bottom >= element.top && screen.top
onBottomPassed Element’s bottom edge has passed top of screen screen.top >= element.bottom

Grouped Events

allows you to specify a collection of callbacks that occur after different percentages or pixels of an element are passed

Event Occurs Example
onPassed {} A distance from the top of an element’s content has been passed, either as a percentage or in pixels

onPassed: {
40: function() {
// do something when having passed 40 pixels.
},
‘80%’: function() {
// do something at 80%
}
}

Reverse Events

Reverse events will occur under the same conditions but as a user scrolls back up the page.

Event Occurs Pseudocode
onTopVisibleReverse Element’s top edge has not passed bottom of screen screen.bottom >= element.top
onTopPassedReverse Element’s top edge has not passed top of the screen screen.top >= element.top
onBottomVisibleReverse Element’s bottom edge has not passed bottom of screen screen.bottom >= element.top
onPassingReverse Element’s top has not passed top of screen but bottom has screen.bottom >= element.top && screen.top
onBottomPassedReverse Element’s bottom edge has not passed top of screen screen.top >= element.bottom

Skipping rendering work with content-visibility #

It may be hard to figure out which containment values to use, since browser optimizations may only kick in when an appropriate set is specified. You can play around with the values to see what works best, or you can use another CSS property called to apply the needed containment automatically. ensures that you get the largest performance gains the browser can provide with minimal effort from you as a developer.

The content-visibility property accepts several values, but is the one that provides immediate performance improvements. An element that has gains , and containment. If the element is off-screen (and not otherwise relevant to the user—relevant elements would be the ones that have focus or selection in their subtree), it also gains containment (and it stops and its contents).

What does this mean? In short, if the element is off-screen its descendants are not rendered. The browser determines the size of the element without considering any of its contents, and it stops there. Most of the rendering, such as styling and layout of the element’s subtree are skipped.

As the element approaches the viewport, the browser no longer adds the containment and starts painting and hit-testing the element’s content. This enables the rendering work to be done just in time to be seen by the user.

#493 – Setting the Visibility of a User Interface Element

February 13, 2012

You can set the visibility of any element that inherits from UIElement by settings its Visibility property to one of the three values listed below.  Because every child hosted in a panel derives from UIElement, this is how you hide/show child elements in a panel.

Values for Visibility (of type System.Windows.Visibility):

  • Visible – element is displayed
  • Hidden – element is not displayed, but the space where it is located is preserved
  • Collapsed – element is not displayed and space for it is not preserved

Below is an example that lets a user toggle between the three possible values for the Visibility of the middle Label.

    <StackPanel>
        <StackPanel Orientation="Horizontal" Margin="10">
            <Label Content="Snoopy" Margin="3" Background="BurlyWood"/>
            <Label Content="Waldo" Margin="3" Background="Thistle"
                   Visibility="{Binding ElementName=cboVisibility, Path=SelectedValue, Converter={StaticResource cboVisibilityConverter}}"/>
            <Label Content="Dagwood" Margin="3" Background="LightGreen"/>
        </StackPanel>
        <ComboBox Name="cboVisibility" HorizontalAlignment="Center" SelectedIndex="0">
            <ComboBox.Items>
                <ComboBoxItem Content="Visible"/>
                <ComboBoxItem Content="Collapsed"/>
                <ComboBoxItem Content="Hidden"/>
            </ComboBox.Items>
        </ComboBox>
        <Label Content="Select visibility of middle Label" HorizontalAlignment="Center"/>
    </StackPanel>
Гость форума
От: admin

Эта тема закрыта для публикации ответов.