Styling an indefinite number of div IDs with CSS

Hi there,

Currently - I am using the “checkbox hack” to show/hide some divs on a page. The problem is, the page will be dynamic so the number of Divs will change. For instance, it may be like this:

<label for="toggle-1"> Label here </label>
<input type="checkbox" id="toggle-1">
<div class="description-1"><h6>Description</h6> Some words here. </div>

Or it may be like this:

<label for="toggle-1"> Label here </label>
<input type="checkbox" id="toggle-1">
<div class="description-1"><h6>Description</h6> Some words here. </div>

<label for="toggle-2"> Label here </label>
<input type="checkbox" id="toggle-2">
<div class="description-2"><h6>Description</h6> Some words here. </div>

There may also be 3, or 4 or more… you get the picture.

My CSS for showing and hiding the description Divs separately is currently setup like this:

/* Default State */
div.description-1,
div.description-2 {
   display: none;
   font-size: 14px;
   padding: 10px;
}

/* Toggled State */
input[type=checkbox]:checked ~ div.description-1,
input[type=checkbox]:checked ~ description-2 {
	display: block;
}

But with an indeterminable amount of Divs that obviously can’t work.

Is there a way in CSS to put a kind of “wildcard” where the number is? So it would say something like

div.description-* {
display: none;
}

input[type=checkbox]:checked ~ div.description-* {
display: block;
},

Assuming the html structure is consistent you can do this.

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style>
/* Default State */
div[class^=description]{
   display: none;
   font-size: 14px;
   padding: 10px;
}

/* Toggled State */
input[type=checkbox]:checked + div[class^=description] {
	display: block;
}

</style>
</head>

<body>

<label for="toggle-1"> Label here </label>
<input type="checkbox" id="toggle-1">
<div class="description-1"><h6>Description</h6> Some words here. </div>

<label for="toggle-2"> Label here </label>
<input type="checkbox" id="toggle-2">
<div class="description-2"><h6>Description</h6> Some words here. </div>

</body>
</html>

Of course in that structure you could just have said :

/* Toggled State */
input[type=checkbox]:checked + div {
	display: block;
}
1 Like

Two things, firstly what you have uses the General Sibling selector ~ which does not descriminate, so when you check the first box, you see both descriptions. Better to use the Adjacent Sibling + selector instead for this.

To the actual question. Why such specific classes for each item?
Using a generic class will apply the rules to any number of objects.

I didn’t explain it above but you can use an attribute selector to match the first part of a string.

i.e. div[class^=description]{etc...}

Of course you don’t really need different class names as already pointed out above anyway,

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.