CSS implements element hiding

1. display:none

Go to the code and set the element display: None; Later, the elements are hidden and the original space is released. It means you don’t take up space after you hide it.

Here’s an example:

Now we have two boxes 1 and 2, and we give box 1 display: None;

display: none;
Copy the code

Box 1 is hidden and its original position is released, and box 2 comes up.

2. visibility:hidden

visibility:hidden; Hide elements, but the space occupied by the element is not released, meaning that things are not seen, but the location is still occupied. If there’s a box down there, you can’t get up there.

Here’s an example:

visibility:hidden
Copy the code

(Note that the parent element is undefined :hidden; The child elements in the box can be displayed separately, meaning that the parent box is hidden, but the child elements can be displayed.

3. opacity:0

After opacity is set, elements are invisible, but their position remains unchanged. This property not only causes the transparency of the current element to change, but also changes with the descendants of the current element.

If a box is set to opacity:0; Then it and its descendants will all be transparent together. And descendant elements cannot be set to display separately.

4. Definitely locate where you can’t see

This is a novel approach.

/* The parent element is set to absolute position */ * the child element is set to absolute position, and then the top and left values are enlarged */ position:absolute; top:-9999999px; left:-99999999px;Copy the code

At this point the element flies out of sight of the browser viewport. Change the top and left values when you need to display elements.

Conclusion contrast

There are four ways to hide elements in this article. Now make a simple comparison.

  • visibility:hidden; Elements are hidden, but take up space. Child elements can be set to display separately
  • display:none; — Elements are hidden and do not take up space
  • opacity:0; — Actually changing the transparency of an element takes up space and affects descendant elements that cannot be displayed alone
  • Absolutely positioned out of visual range – Absolutely positioned elements are removed from the standard document flow and do not occupy position.