search
HomeWeb Front-endFront-end Q&AHow to implement click-to-hide display in css

CSS Click to Hide Show

In today’s Internet era, the focus of web design has shifted from simple static display to a more advanced interactive experience. Among them, hiding and showing is one of the most commonly used interaction methods. This method allows users to obtain the required information more conveniently and can greatly reduce redundant content on the page. In CSS, there are several methods to hide and show, and this article will introduce them one by one.

  1. Use the display attribute

The value of the display attribute in CSS controls whether the element is displayed or hidden. Values ​​include:

  • none: The element will be completely removed from the page and will be completely invisible to the layout.
  • block: The element is displayed as a block-level element, meaning it occupies an entire line.
  • inline: The element is displayed as an inline element, meaning it takes up the same space as the text.
  • inline-block: The element is displayed as an inline element, but attributes such as width and height can be set.

Using the display attribute, we can hide and display by adding or removing the display attribute of the element. The sample code is as follows:

HTML code:

<div>
  <p>隐藏的内容</p>
</div>
<button>显示/隐藏</button>

CSS Code:

.box {
  display: none;
}

JavaScript code:

document.getElementById("toggle").addEventListener("click", function() {
  var box = document.querySelector(".box");
  if(box.style.display === "none") {
    box.style.display = "block";
  } else {
    box.style.display = "none";
  }
});
  1. Use the opacity attribute

The opacity attribute controls the transparency of the element to achieve the effect of hiding or showing. When the opacity property is set to 0, the element will be completely transparent, so it cannot be seen. When the opacity property is 1, it is fully visible. But it will still take up its space on the page.

HTML code:

<div>
  <p>隐藏的内容</p>
</div>
<button>显示/隐藏</button>

CSS code:

.box {
  opacity: 0;
  transition: opacity 0.5s ease-in-out;
  pointer-events: none;
}

.box.show {
  opacity: 1;
  pointer-events: auto;
}

JavaScript code:

document.getElementById("toggle").addEventListener("click", function() {
  var box = document.querySelector(".box");
  box.classList.toggle("show");
});
  1. Use the visibility attribute
## The #visibility attribute controls whether an element is hidden but still retains its space, it does not completely remove the element from the page. When the visibility property is set to hidden, the element will be hidden but will still take up its space on the page. When the visibility property is visible, it is fully visible.

HTML code:

<div>
  <p>隐藏的内容</p>
</div>
<button>显示/隐藏</button>
CSS code:

.box {
  visibility: hidden;
}

.box.show {
  visibility: visible;
}
JavaScript code:

document.getElementById("toggle").addEventListener("click", function() {
  var box = document.querySelector(".box");
  box.classList.toggle("show");
});
To sum up, whether it is display, opacity or visibility attributes, They can both hide and show. Each of these three methods has its own advantages and disadvantages, and we can choose the appropriate method according to actual needs.

The above is the detailed content of How to implement click-to-hide display in css. 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
React's SEO-Friendly Nature: Improving Search Engine VisibilityReact's SEO-Friendly Nature: Improving Search Engine VisibilityApr 26, 2025 am 12:27 AM

Yes,ReactapplicationscanbeSEO-friendlywithproperstrategies.1)Useserver-siderendering(SSR)withtoolslikeNext.jstogeneratefullHTMLforindexing.2)Implementstaticsitegeneration(SSG)forcontent-heavysitestopre-renderpagesatbuildtime.3)Ensureuniquetitlesandme

React's Performance Bottlenecks: Identifying and Optimizing Slow ComponentsReact's Performance Bottlenecks: Identifying and Optimizing Slow ComponentsApr 26, 2025 am 12:25 AM

React performance bottlenecks are mainly caused by inefficient rendering, unnecessary re-rendering and calculation of component internal heavy weight. 1) Use ReactDevTools to locate slow components and apply React.memo optimization. 2) Optimize useEffect to ensure that it only runs when necessary. 3) Use useMemo and useCallback for memory processing. 4) Split the large component into small components. 5) For big data lists, use virtual scrolling technology to optimize rendering. Through these methods, the performance of React applications can be significantly improved.

Alternatives to React: Exploring Other JavaScript UI Libraries and FrameworksAlternatives to React: Exploring Other JavaScript UI Libraries and FrameworksApr 26, 2025 am 12:24 AM

Someone might look for alternatives to React because of performance issues, learning curves, or exploring different UI development methods. 1) Vue.js is praised for its ease of integration and mild learning curve, suitable for small and large applications. 2) Angular is developed by Google and is suitable for large applications, with a powerful type system and dependency injection. 3) Svelte provides excellent performance and simplicity by compiling it into efficient JavaScript at build time, but its ecosystem is still growing. When choosing alternatives, they should be determined based on project needs, team experience and project size.

Keys and React's Reconciliation Algorithm: Improving PerformanceKeys and React's Reconciliation Algorithm: Improving PerformanceApr 26, 2025 am 12:21 AM

KeysinReactarespecialattributesassignedtoelementsinarraysforstableidentity,crucialforthereconciliationalgorithmwhichupdatestheDOMefficiently.1)KeyshelpReacttrackchanges,additions,orremovalsinlists.2)Usingunique,stablekeyslikeIDsratherthanindicespreve

The Boilerplate Code Required for React Projects: Reducing Setup OverheadThe Boilerplate Code Required for React Projects: Reducing Setup OverheadApr 26, 2025 am 12:19 AM

ToreducesetupoverheadinReactprojects,usetoolslikeCreateReactApp(CRA),Next.js,Gatsby,orstarterkits,andmaintainamodularstructure.1)CRAsimplifiessetupwithasinglecommand.2)Next.jsandGatsbyoffermorefeaturesbutalearningcurve.3)Starterkitsprovidecomprehensi

Understanding useState(): A Comprehensive Guide to React State ManagementUnderstanding useState(): A Comprehensive Guide to React State ManagementApr 25, 2025 am 12:21 AM

useState()isaReacthookusedtomanagestateinfunctionalcomponents.1)Itinitializesandupdatesstate,2)shouldbecalledatthetoplevelofcomponents,3)canleadto'stalestate'ifnotusedcorrectly,and4)performancecanbeoptimizedusinguseCallbackandproperstateupdates.

What are the advantages of using React?What are the advantages of using React?Apr 25, 2025 am 12:16 AM

Reactispopularduetoitscomponent-basedarchitecture,VirtualDOM,richecosystem,anddeclarativenature.1)Component-basedarchitectureallowsforreusableUIpieces,improvingmodularityandmaintainability.2)TheVirtualDOMenhancesperformancebyefficientlyupdatingtheUI.

Debugging in React: Identifying and Resolving Common IssuesDebugging in React: Identifying and Resolving Common IssuesApr 25, 2025 am 12:09 AM

TodebugReactapplicationseffectively,usethesestrategies:1)AddresspropdrillingwithContextAPIorRedux.2)HandleasynchronousoperationswithuseStateanduseEffect,usingAbortControllertopreventraceconditions.3)OptimizeperformancewithuseMemoanduseCallbacktoavoid

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 Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.