Show content in CSS only if the div element does not contain any child elements

Is there a way to show or hide a div conditionally based on the content of another div, using only CSS? I want to avoid using JavaScript.

In the past, I've used a workaround like this:

.myClass:empty:before {
    content: 'content added to empty div';
}
  • This method works for adding content to an empty div. However, it doesn't support creating hyperlinks in the generated pseudo-content. That's why I'm exploring other options.

Let's say my current div structure looks like this:

<div class="div1"></div>
<div class="div2">This should be displayed</div>

Is there a CSS technique that can display div2 if div1 is empty, but hide it if div1 has any content?

Feel free to suggest alternative ways to organize the div elements, as long as they achieve the desired outcome regardless of the current structure.

I'm open to ideas and suggestions. Thank you.

Answer №1

Here is a recommended CSS code:

/* Hide the div.div2 element and its content
   if it follows div.div1: */
div.div1 + div.div2 {
    display: none;
}

/* Display the div.div2 element that follows
   an empty div.div1 element: */
div.div1:empty + div.div2 {
    display: block;
}

/* Hide the div.div2 element and its content
       if it follows div.div1: */
div.div1 + div.div2 {
  display: none;
}

/* Display the div.div2 element that follows
       an empty div.div1 element: */

div.div1:empty + div.div2 {
  display: block;
}

div.div1 {
  border: 1px solid #f00;
  color: #f00;
}

div.div2 {
  color: #0f0;
  border: 1px solid #0f0;
  margin-bottom: 1em;
}
<div class="div1"></div>
<div class="div2">This content will be shown.</div>

<div class="div1">This is 'div.div1' (it has content)</div>
<div class="div2">This content will not be displayed.</div>

Answer №2

implement css selector for next element

.div1:empty + div{
    content: 'content inserted into empty div';
}

Answer №3

Gratitude for the prompt responses. Following Alexis Peters' suggestion, I implemented this solution which worked seamlessly. Documenting it here for future use:

div2 {
    display: none;
}

.div1:empty + .div2{
    display: block;
}

For those curious minds like mine, the CSS above essentially instructs to "hide div2 by default. If any .div2 comes after an empty .div1 element, make it visible".

Cheers.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to trigger the onclick event from different controls

I have a videojs player and a button on my html page. The videojs player supports the functionality to pause/play the video when clicked. I want to trigger this event by clicking on my button. How can I achieve this? Here is the code that I tried, but it ...

Unable to retrieve HTML code with PHP's file_get_contents function

I have been trying to retrieve the HTML content of a webpage using the code below: $url = "http://mysmallwebpage.com/"; $html = file_get_contents($url); Unfortunately, it seems that the file_get_contents function is unable to open URLs in certain formats ...

The Bootstrap Library reference causes the anchor hover function to malfunction

Feeling frustrated after encountering an issue where the Bootstrap button class interferes with the hover function in standard CSS. Decided to create a custom solution by adding a grey box next to the button to display hover information instead of using t ...

The inability for two dynamically created Ajax elements to identify one another is hindering their interaction

Hello wonderful people at Stack Overflow, I've been attempting to create a table generator that dynamically creates two tables upon the click of a button. So far, it's been quite a frustrating journey full of roadblocks... Currently, my approac ...

Using HTML and JavaScript to add variables into the URL within the window.location

I have been struggling to incorporate longitude and latitude into the URL. Despite researching various topics online, I have not found a solution that works for me. Below is the HTML code that showcases the issue. When you click the "Show Position" button ...

What's the best way to include CSS and Javascript in an HTML document?

I'm still getting the hang of CSS and JavaScript. I stumbled upon a cool countdown timer that I'd like to incorporate into my website, but I'm not quite sure how to place it where I envision it. Check out the timer here CSS: html,body{mar ...

Understanding the fundamentals of positioning elements in CSS as they float on a webpage

Understanding the behavior of float in CSS can be confusing. When floating an element to the left or to the right, it affects how other elements wrap around it. But why do some elements wrap while others don't? For example, when you have a floated im ...

Updating the CSS class for a particular text segment enclosed in a <p> or <span> element

My <p> tag is set to contain several lines of text with a specific CSS class, but I am looking to modify the text format within certain parts of the paragraph. In the past, I would achieve this using the <font> tag, however it seems that HTML5 ...

Assistance required for posting Jquery files

Attempted to upload a file using jQuery with a hidden form and an Input element, triggering the file browser with jQuery. The changed input is then sent to a PHP server script. Encountered an issue where submitting the form with $("form1").submit(); worke ...

retrieving data from a database to populate selection options using PHP

While working on our thesis, I encountered a challenge where I needed to transfer certain values from my SQL database to another part of the project. Below is a snippet of the sample code I was using: <tr> <td id="t" align="center"> ...

Exploring the Integration of Metro CSS 3 Form Validation within the MVC Framework

I am looking to implement the form validator feature from Metro CSS 3 in my MVC 5 application. Below is a snippet of my code: @using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" })) { @Html. ...

How can I position one DIV relative to another DIV?

Can a DIV be positioned relative to another DIV? My guess is that it involves nesting it inside the reference DIV and utilizing position: relative. However, I'm struggling with how to achieve this without impacting the content of the reference DIV. An ...

Is there a way to retrieve the aria-label attribute value from this specific WebElement?

When utilizing Java Selenium, I have access to a WebElement object that corresponds to the following HTML node: <td role="gridcell" class="mat-calendar-body-cell ng-star-inserted" style="width: 25%; padding-top: 7.14286%; paddin ...

Customize hover effects in tailwind css with dynamic values

I am trying to customize the text color on hover based on different category names using tailwind CSS. In my configuration, I have assigned a specific color code for each category like this : tailwind.config.js theme: { extend: { } }, co ...

Having trouble with an echoing PHP code error?

When I try to display my PHP code on the website, it is not showing up properly and instead displaying random numbers. I am attempting to add a feature to my website where the text updates every week from a stored file called quotes.txt. Can anyone advise ...

Having trouble showing Bootstrap Toasts on my website

I successfully implemented Toast functionality upon button click, but I am facing an issue where I have two buttons and I want a separate Toast to appear for each button click. How can I achieve this? Another problem I encountered is related to the docume ...

Guide on centering an unfamiliar element in the viewport using HTML, CSS, and JavaScript

In the process of developing my VueJS project, I have successfully implemented a series of cards on the page. However, I am now facing a challenge - when a user selects one of these cards, I want it to move to the center of the screen while maintaining its ...

Inject the HTML code into a bash script and perform operations on it

Could someone help me with a bash scripting question? I'm new to this, so I may have missed it if it's already been answered. I want to pass the html source code of a web page to my script, which will then modify or scrape the web page of its HT ...

Is your display:inline-block feature not functioning properly?

I am currently designing the homepage for this website and I am attempting to arrange the category divs under the header in a grid layout, with 3 divs per row. I have been trying to achieve this using display:inline-block, but so far, I can only get the d ...

Achieve text length that does not exceed the specified limit dynamically

Is it possible to determine the length of the visible portion of text that overflows (or calculate the size of the overflow for further processing) using CSS or JavaScript? If so, can this calculation be done dynamically (such as on window resize)? The g ...