search
HomeWeb Front-endCSS TutorialHow to hide css elements

How to hide css elements

Nov 15, 2018 pm 05:14 PM
csshidden element

How to hide css elements? This article will introduce you to 5 ways to hide css elements, so that you can understand how you can hide css elements, and the nuances you need to remember when using these methods to hide elements. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

First of all, let’s briefly introduce 5 ways to hide css elements, which are:

1. Use the opacity attribute to hide elements

2. Use the visibility attribute to hide elements

3. Use the display attribute to hide elements

4. Use the position attribute to hide elements

5. Use the clip-path attribute to hide elements.

Let’s introduce these 5 methods of hiding CSS elements in detail so that everyone can understand the subtle differences between them.

opacity attribute

The opacity attribute hides an element by setting its transparency. It's designed not to change the element's bounding box in any way. This means that setting the opacity to zero only visually hides the element; the element still takes its position and affects the layout of the page, and it also responds to user interaction.

.hide {
  opacity: 0;
}

If you plan to use the opacity attribute to hide an element from screen readers, unfortunately this is not possible. Because screen readers will read the element and all its contents just like every other element on the web page.

I should also mention that the opacity property is animated and used to create some great effects. Example:

HTML code:

<div>1</div>
<div class="o-hide">2</div>
<div>3</div>

css code:

.o-hide {
  opacity: 0;
  transition: all ease 0.8s;
}

.o-hide:hover {
  opacity: 1;
}

Rendering:

How to hide css elements

When hovering the mouse When stopped on the hidden second block, the element will smoothly transition from fully transparent to fully opaque. The module also sets the cursor:pointer to show that it can interact with it.

visibility attribute

The visibility attribute hides the element by setting whether it is visible. Setting the visibility attribute to hidden will hide our element.

The visibility attribute is the same as the opacity attribute. Hidden elements will still affect the layout of our web page. The only difference is that this time it won't capture any user interaction when the user is hidden. Additionally, the element will also be hidden from screen readers.

This property can also be animated as long as the initial state and final state have different values. This ensures that transitions between visibility states can be smooth rather than abrupt.

This demo shows the difference between visibility and opacity:

HTML code:

<div>1</div>
<div class="o-hide"><p>2</p></div>
<div>3</div>

css code:

.o-hide {
  visibility: hidden;
  transition: all ease 0.8s;
}
.o-hide:hover {
  visibility: visible;
}
.o-hide p {
  visibility: visible;
  margin: 0;
  padding: 0;
}

js code:

var oHide = document.querySelector(".o-hide");
var oHideP = document.querySelector(".o-hide p");
var count = oHideP.innerHTML;

oHide.addEventListener("click", function(){
    count++;
    oHideP.innerHTML = count;
});

Rendering:

How to hide css elements

Please note that if the attribute is explicitly set to visibility, the descendants of the element with visibility set to hidden will still be visible. Try hovering over the hidden element instead of the inner paragraph and you will see that the cursor does not change to a pointer. Additionally, if you try to click on the element, your click will not be responded to.

The

tag within the

tag will still capture all mouse events. As you hover over the text, the
itself becomes visible and starts responding to events.

display attribute

The display attribute truly hides the element. Setting the value of the display attribute to none ensures that it is not generated at all. Box model; and using this property, no empty space is left when hiding the element. Not only that, but as long as display is set to none, any direct user interaction is not possible. Additionally, screen readers will not read the element's content. It's as if the element doesn't exist.

However, all descendants of our element will also be hidden. This property cannot be animated, so transitions between states are always abrupt.

Please note that the element is still accessible through the DOM. You can manipulate it like any other element. Example:

HTML code:

<div>Hover!</div>
<div class="o-hide"><p>0</p></div>
<div>0</div>

css code:

.o-hide {
  display: none;
  transition: all ease 0.8s;
}

.o-hide:hover {
  display: block;
}

.o-hide p {
  display: block;
  margin: 0;
  padding: 0;
}

js code:

var count = 0;
var oHide = document.querySelector(".o-hide");
var firstDiv = document.querySelector("div:nth-child(1)");

firstDiv.addEventListener("mouseover", function(){
    count++;
    oHide.innerHTML = &#39;<p>&#39; + count + &#39;</p>&#39;;
});

firstDiv.addEventListener("click", function(){
  oHide.style.display = "block";
});

Rendering:

How to hide css elements

You can see that the second block has a p paragraph with its display attribute set to block, but the paragraph is still invisible. This is a difference between visibility: hidden and display: none. In the first case, any descendants that explicitly set visibility to visible will become visible, but this will not happen in the display property. After setting display: none, all descendants are hidden, regardless of their display value.

Now, hover over the first block of the demo a few times. Ever wandered? Click on the first block. This should make the second block visible. The count inside should now be a number other than zero. This is because even elements that are hidden from the user can still be manipulated using JavaScript

position属性

假设你有一个要与之交互的元素,但又不希望它影响网页布局。到目前为止,没有任何属性可以正确处理这种情况。在这种情况下,你可以做的一件事,那就是将元素移出视图窗口。这样它不会影响布局,仍然可以操作。

以下演示说明绝对定位如何隐藏元素和工作方式与上一个演示大致相同(html代码一样):

css代码:

.o-hide {
  position: absolute;
  top: -9999px;
  left: -9999px;
}

.o-hide:hover {
  position: static;
}

js代码:

var count = 0;
var oHide = document.querySelector(".o-hide");
var firstDiv = document.querySelector("div:nth-child(1)");

firstDiv.addEventListener("mouseover", function(){
    count++;
    oHide.innerHTML = count;
});

firstDiv.addEventListener("click", function(){
    oHide.style.position = "static";
});

效果图:

How to hide css elements

这里的主要思想是将负的顶部和左侧值设置得足够高,以使元素在屏幕上不再可见。该技术的一个好处(或潜在的缺点)是屏幕阅读器可以读取绝对定位元素的内容。这是完全可以理解的,因为你只将元素移出视图窗口,以便用户无法看到它。

你应该避免使用此方法隐藏任何可以获得焦点的元素,因为当用户关注该元素时会导致意外跳转。此方法经常用于创建自定义复选框或单选按钮。

clip-path属性

隐藏元素的另一种方法是剪切它们。以前,这可以通过clip属性来完成,但是已经弃用了有利于更好的属性clip-path。

请注意,IE或Edge尚未完全支持下面clip-path属性值的使用。这是一个展示它的示例演示:

css代码:

.o-hide {
  clip-path: polygon(0px 0px, 0px 0px, 0px 0px, 0px 0px);
}

js代码:

var count = 0;
var oHide = document.querySelector(".o-hide");
var firstDiv = document.querySelector("div:nth-child(1)");

firstDiv.addEventListener("mouseover", function(){
    count++;
    oHide.innerHTML = count;
});


firstDiv.addEventListener("click", function(){
    oHide.className = "";
});

效果图:

How to hide css elements

如果将鼠标悬停在第一个元素上,它仍然可以影响第二个元素,即使它被clip-path属性隐藏。如果单击该元素,它将删除隐藏的类以显示我们一直存在的元素。这个文本仍然可以被屏幕阅读器阅读。

即使我们的元素不再可见,它周围的元素仍然表现得像它原来的矩形尺寸。请记住,在悬停区域之外,像悬停或点击等用户交互是不可能的。在我们的例子中,这意味着用户将无法直接与隐藏元素交互。此外,该属性能够以各种方式被动画化以产生新的效果。

总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。

The above is the detailed content of How to hide css elements. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
@keyframes vs CSS Transitions: What is the difference?@keyframes vs CSS Transitions: What is the difference?May 14, 2025 am 12:01 AM

@keyframesandCSSTransitionsdifferincomplexity:@keyframesallowsfordetailedanimationsequences,whileCSSTransitionshandlesimplestatechanges.UseCSSTransitionsforhovereffectslikebuttoncolorchanges,and@keyframesforintricateanimationslikerotatingspinners.

Using Pages CMS for Static Site Content ManagementUsing Pages CMS for Static Site Content ManagementMay 13, 2025 am 09:24 AM

I know, I know: there are a ton of content management system options available, and while I've tested several, none have really been the one, y'know? Weird pricing models, difficult customization, some even end up becoming a whole &

The Ultimate Guide to Linking CSS Files in HTMLThe Ultimate Guide to Linking CSS Files in HTMLMay 13, 2025 am 12:02 AM

Linking CSS files to HTML can be achieved by using elements in part of HTML. 1) Use tags to link local CSS files. 2) Multiple CSS files can be implemented by adding multiple tags. 3) External CSS files use absolute URL links, such as. 4) Ensure the correct use of file paths and CSS file loading order, and optimize performance can use CSS preprocessor to merge files.

CSS Flexbox vs Grid: a comprehensive reviewCSS Flexbox vs Grid: a comprehensive reviewMay 12, 2025 am 12:01 AM

Choosing Flexbox or Grid depends on the layout requirements: 1) Flexbox is suitable for one-dimensional layouts, such as navigation bar; 2) Grid is suitable for two-dimensional layouts, such as magazine layouts. The two can be used in the project to improve the layout effect.

How to Include CSS Files: Methods and Best PracticesHow to Include CSS Files: Methods and Best PracticesMay 11, 2025 am 12:02 AM

The best way to include CSS files is to use tags to introduce external CSS files in the HTML part. 1. Use tags to introduce external CSS files, such as. 2. For small adjustments, inline CSS can be used, but should be used with caution. 3. Large projects can use CSS preprocessors such as Sass or Less to import other CSS files through @import. 4. For performance, CSS files should be merged and CDN should be used, and compressed using tools such as CSSNano.

Flexbox vs Grid: should I learn them both?Flexbox vs Grid: should I learn them both?May 10, 2025 am 12:01 AM

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)May 09, 2025 am 09:57 AM

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSS Animations: Is it hard to create them?CSS Animations: Is it hard to create them?May 09, 2025 am 12:03 AM

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use