Conceal an entire div using CSS, especially if a portion of it remains unoccupied

Is there a way to conceal an entire division if a part of it is void? For instance, if "dd" is empty as indicated below, can I hide the entire class "test" so that the keyword Restrictions does not display either? I attempted .test dd:empty { display: none; } but that method did not produce any results. Thank you!

  <div class="test"><dt>Restrictions:</dt>
  <dd></dd></div>

Answer №1

If you're looking to achieve a specific functionality using only CSS, it might be challenging. It could be more efficient to test it on the server-side if possible. However, in cases where that's not feasible, you can use some JavaScript code to accomplish the task.

<script type="text/javascript">
// handles multiple dt/dd pairs per div and hides them each conditionally
function hideIfEmpty() {

    // get all the elements with class test
    var els = document.getElementsByTagName('dl');
    // for every 'test' div we find, go through and hide the appropriate elements
    Array.prototype.map.call(els, function(el) {
        var children = el.childNodes;
        var ddEmpty = false;
        for(var i = children.length - 1; i >= 0; i--) {
            if(children[i].tagName === 'DD' && !children[i].innerHTML.trim()) {
                ddEmpty = true;
            } else if(children[i].tagName === 'DT') {
                if(ddEmpty) {
                    children[i].style.display = 'none';
                }
                // reset the flag
                ddEmpty = false;
            }
        }
    });

}

window.addEventListener('load', hideIfEmpty);
</script>

<div class="test">
    <div style="clear: both;"></div>
    <dl>
        <dt>Restrictions:</dt>
        <dd></dd>
        <dt>Other Restrictions:</dt>
        <dd>Since I have content, I won't be hidden.</dd>
    </dl>
</div>

It's important to note that the provided code may not be compatible with older versions of Internet Explorer due to functions like Array.prototype.map, String.prototype.trim, and addEventListener. You can utilize polyfills for these or implement your own alternatives easily (like using a for loop instead).

Answer №2

You can't achieve that with CSS alone. You'll either need to use JavaScript to find and hide empty elements along with their parents, or have your CMS add specific CSS classes for pages with no content.

Responding as per the request of @Barett.

Answer №3

If you want to update your CSS, consider the following:

.sample{ 
visibility: hidden; 
background-color: transparent;
}

Even though making the text transparent will hide it, using visibility:hidden should achieve the same result.


To ensure that the div with the ID "sample" is only visible when the dd tag is empty, and if you are using jQuery, you can implement the following JavaScript in combination with the CSS:

if($("dd").html().length == 0) {
show();
}

Please note that this solution relies on jQuery, a JavaScript library.

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

In Android Kitkat 4.4.4, the Ionic navbar displays icons vertically when using the <ion-buttons end> feature

When viewing in the browser with ionic serve, everything looks fine. However, on an Android Kitkat device running version 4.4.4, the buttons on the right side of the navbar are displaying vertically instead of horizontally. <ion-navbar> <ion-ti ...

What is the best way to showcase a full-screen overlay directly inside an iFrame?

As I work in HTML, I'm faced with a challenge - my iFrame is only taking up a small section of the screen (referred to as 'World' in the example below). What I want to achieve is creating a full-screen div overlay from that iFrame, but curr ...

What is the best method to override the CSS transition effect with JavaScript?

I am trying to implement a CSS transition where I need to reset the width of my box in advance every time my function is called. Simply setting the width of the box to zero makes the element shrink with animation, but I want to reset it without any animati ...

Is there a way to make all Bootstrap column heights equal using only jQuery?

I am currently working on matching the heights of two columns without using an existing library like match-height.js. In this specific case, I have a row with 2 columns where the first column contains a centered black square and the second column contains ...

Addressing three visual problems with an html form input, dropdown menu, and clickable button

Currently, the output of my code looks like this: https://i.stack.imgur.com/pl5CJ.jpg The first box (squared) represents an <input>, while the second box (rectangled) is a <select>. There are several issues that I am facing: The text entered ...

Discovering elements with Selenium through XPATH or CSS Selector

Having trouble locating the "import" element using Selenium Webdriver in C#. I've attempted the following codes but haven't had any luck: driver.FindElement(By.XPath("//*[@class='menu_bg']/ul/li[3]")).Click(); driver.FindElement(By.XPa ...

The content div in CSS is causing the menu div to be displaced

I have encountered a difficulty in describing the issue at hand as I am still in the learning phase and consider myself a beginner. Within my container div, there are two other divs - one for the menu and another for the content. Both of these divs float ...

Achieving overlapping of a <div> element with a "position: fixed" container while enabling vertical scrolling of the fixed container's content

In my single page application, I have a fixed container and I am trying to make one div inside this container overlap the boundaries of the fixed container while also vertically scrolling with its contents. Unfortunately, I have only been able to achieve e ...

Ways to Adjust the Earth's Position in WebGL Earth

I have been working with this WebGL Earth component for my project, but I am facing difficulty in adjusting the position of the planet on the canvas. My intention was to place the planet at the bottom of the page, but I haven't been able to achieve th ...

What could be causing my page's wrapper to shrink upon logging in?

After logging out, the background of my page wrapper expands to cover 100% of the page. However, once you log back in, it shrinks and adjusts to the width of the member bar... TO TEST USER ACCOUNT BELOW: USERNAME: TEST PASSWORD: TEST123 HTML FOR LOGGED ...

Putting an <input/> element inside a Material UI's <TextField/> component in ReactJS - a beginner's guide

I am attempting to style <TextField/> (http://www.material-ui.com/#/components/text-field) to resemble an <input/>. Here is what I have tried: <TextField hintText='Enter username' > <input className="form-control ...

Utilizing a dropdown feature in Bootstrap for creating X columns of lists instead of a traditional single list

Check out my Fiddle. Beneath Dropdown1 lies a single-column list of actions. I'm looking to expand this list across multiple columns, like 5 or the width of the page. I'm hoping there's a Bootstrap CSS class I can use for this, but I migh ...

Modifying button appearance based on state change in AngularJS

I have a button with a grey color and I want to create two different states for it: one that is selected (blue) and another that is in an idle state (grey). Currently, I am working on Angularjs but I am fairly new to this platform. Could you kindly provid ...

What's the Reason Behind the Ineffectiveness of Footer Background Color in HTML CSS3?

Having some trouble setting the background color for my footer to something other than white. I've been able to successfully change the background of other layout elements, but the footer is giving me issues. Check out the code below: <footer> ...

Displaying every nth image in a new row of a CSS grid

I have a react component and I want to arrange 3 photos inline in a row with their names below each photo, and then continue in new rows for the next set of 3 elements and so on... I attempted to use :nth-child(3n+1) but encountered some issues... const P ...

Text within the footer section

When displaying the name of a subcategory, I want it in one line. However, if the subcategory name contains two words, it should be displayed in two lines. https://i.stack.imgur.com/CcDeL.png Code: .Footer { width: 100%; display ...

Tips for styling row headers in Vaadin with CSS

I am in need of assistance with a problem I am facing. Recently, I started learning the Vaadin framework and I am trying to apply CSS to the row headers (first cell of each row), but so far I have not had any success. Below is the code that I have been usi ...

What is the best way to stop Quasar dropdown list from moving along with the page scroll?

I am facing an issue with my code while using Quasar (Vue 3.0). The code snippet in question is: <q-select filled v-model="model" :options="options" label="Filled" /> When the drop-down menu is open and I scroll the pag ...

Which internet browsing engine does Android leverage for phonegap applications?

Currently, I'm working on incorporating CSS animations into a phone gap project. Surprisingly, the animations work flawlessly on an iOS device but encounter issues on my Android device. Strangely, elements like dashed borders are not even showing up. ...

Tips for avoiding anti-aliasing of bitmap font on Internet Explorer and Firefox

I am currently experiencing issues with font smoothing when using a basic bitmap font for icons. While the font appears crisp in Chrome, it appears blurry in IE and FF. Do you have any recommendations on how to resolve this problem? You can view a screen ...