search
HomeWeb Front-endFront-end Q&Acss div show hide div

CSS is a very important technology in web design and development, where showing and hiding elements are common tasks in CSS. In this article, we will introduce how to use CSS to show and hide DIV elements.

In CSS, you can use the display attribute to control the display and hiding of elements. The display attribute can be set to the following values:

  • none (hide the element)
  • block (display the element as a block element)
  • inline (display the element as inline inline-block (displays elements as inline-block elements)
  • The following code example demonstrates how to use the display attribute to hide and show DIV elements:
.hide {
  display: none;
}

.show {
  display: block;
}

The .hide class in the example sets the element display to none, which will cause the element to be hidden. Instead, the .show class sets the element to block, which causes the element to be displayed.

Next, let’s take a look at how to dynamically show and hide DIV elements through JavaScript.

First, we can use the getElementById method to get the reference of the element to be displayed or hidden, and then set the style display property of the element to none or block to hide or display it:

//隐藏元素
var element = document.getElementById("element-id");
element.style.display = "none";

//显示元素
element.style.display = "block";

However, there are some drawbacks to manually controlling the visibility of elements by using JavaScript. First, it requires relatively verbose code and requires explicit handling of element state, which makes the code difficult to maintain. Second, in large websites, dynamically switching the styles of page elements may cause browser performance to degrade.

Therefore, we can use CSS’s :focus pseudo-class to achieve some dynamic element display and hiding effects. When the user clicks on an element, the element can gain focus and apply CSS styles in the :focus state.

For example, in the code below, we define a :focus style for the element that will appear when the user clicks on the element. When the user clicks on another element on the page outside of focus, the element will be hidden again:

.element:focus {
  display: block;
}

.element {
  display: none;
}

When we use the :focus pseudo-class, we don't need to use JavaScript to manage the logic and can do it using just CSS Dynamic elements hide and show. This also makes our code clearer and easier to maintain.

Finally, there is a way to control the display and hiding of elements using CSS and JavaScript, which is based on the HTML checkbox element. When the checkbox is selected, the related elements will be displayed. Otherwise, the element is hidden.

The key to implementing this method is to use CSS’s :checked pseudo-class, which is activated when the element associated with :checked is selected. To achieve this effect, we need to add some CSS rules between the element and the associated checkbox.

The following code demonstrates how to use checkboxes to display and hide elements:

<input type="checkbox" id="checkbox-id">
<label for="checkbox-id">显示隐藏元素</label>
<div class="element">隐藏的元素</div>
/* 隐藏元素 */
.element {
  display: none;
}

/* 复选框被选中时显示元素 */
#checkbox-id:checked ~ .element {
  display: block;
}

In this example, we use a checkbox and an associated label. When the user clicks The checkbox will be selected when labeling. When the checkbox is selected, the .element element's display style will be set to block and the element will be displayed.

To summarize, by using the display attribute of CSS, we can display and hide elements in web design. In some cases, we can use JavaScript or the :focus pseudo-class to achieve dynamic effects, and using checkboxes is another way to achieve this effect. We can choose the method that best suits us based on actual needs.

The above is the detailed content of css div show hide div. 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
What are the limitations of React?What are the limitations of React?May 02, 2025 am 12:26 AM

React'slimitationsinclude:1)asteeplearningcurveduetoitsvastecosystem,2)SEOchallengeswithclient-siderendering,3)potentialperformanceissuesinlargeapplications,4)complexstatemanagementasappsgrow,and5)theneedtokeepupwithitsrapidevolution.Thesefactorsshou

React's Learning Curve: Challenges for New DevelopersReact's Learning Curve: Challenges for New DevelopersMay 02, 2025 am 12:24 AM

Reactischallengingforbeginnersduetoitssteeplearningcurveandparadigmshifttocomponent-basedarchitecture.1)Startwithofficialdocumentationforasolidfoundation.2)UnderstandJSXandhowtoembedJavaScriptwithinit.3)Learntousefunctionalcomponentswithhooksforstate

Generating Stable and Unique Keys for Dynamic Lists in ReactGenerating Stable and Unique Keys for Dynamic Lists in ReactMay 02, 2025 am 12:22 AM

ThecorechallengeingeneratingstableanduniquekeysfordynamiclistsinReactisensuringconsistentidentifiersacrossre-rendersforefficientDOMupdates.1)Usenaturalkeyswhenpossible,astheyarereliableifuniqueandstable.2)Generatesynthetickeysbasedonmultipleattribute

JavaScript Fatigue: Staying Current with React and Its ToolsJavaScript Fatigue: Staying Current with React and Its ToolsMay 02, 2025 am 12:19 AM

JavaScriptfatigueinReactismanageablewithstrategieslikejust-in-timelearningandcuratedinformationsources.1)Learnwhatyouneedwhenyouneedit,focusingonprojectrelevance.2)FollowkeyblogsliketheofficialReactblogandengagewithcommunitieslikeReactifluxonDiscordt

Testing Components That Use the useState() HookTesting Components That Use the useState() HookMay 02, 2025 am 12:13 AM

TotestReactcomponentsusingtheuseStatehook,useJestandReactTestingLibrarytosimulateinteractionsandverifystatechangesintheUI.1)Renderthecomponentandcheckinitialstate.2)Simulateuserinteractionslikeclicksorformsubmissions.3)Verifytheupdatedstatereflectsin

Keys in React: A Deep Dive into Performance Optimization TechniquesKeys in React: A Deep Dive into Performance Optimization TechniquesMay 01, 2025 am 12:25 AM

KeysinReactarecrucialforoptimizingperformancebyaidinginefficientlistupdates.1)Usekeystoidentifyandtracklistelements.2)Avoidusingarrayindicesaskeystopreventperformanceissues.3)Choosestableidentifierslikeitem.idtomaintaincomponentstateandimproveperform

What are keys in React?What are keys in React?May 01, 2025 am 12:25 AM

Reactkeysareuniqueidentifiersusedwhenrenderingliststoimprovereconciliationefficiency.1)TheyhelpReacttrackchangesinlistitems,2)usingstableanduniqueidentifierslikeitemIDsisrecommended,3)avoidusingarrayindicesaskeystopreventissueswithreordering,and4)ens

The Importance of Unique Keys in React: Avoiding Common PitfallsThe Importance of Unique Keys in React: Avoiding Common PitfallsMay 01, 2025 am 12:19 AM

UniquekeysarecrucialinReactforoptimizingrenderingandmaintainingcomponentstateintegrity.1)Useanaturaluniqueidentifierfromyourdataifavailable.2)Ifnonaturalidentifierexists,generateauniquekeyusingalibrarylikeuuid.3)Avoidusingarrayindicesaskeys,especiall

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

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.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools