I am try to skip hidden child while using nth-child(odd) and nth-child(even), but it does not skip those hidden records.
i have the following HTML and CSS code.
<style>
ul {
list-style-type: none;
}
li {
height: 2em;
border: 1px solid black;
}
/* li:not(.hidden):nth-child(odd) { */
li:nth-child(odd) {
background: khaki;
}
li:nth-child(even) {
background: indianred;
}
.hidden {
display: none;
}
</style>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li class="hidden">4</li>
<li class="hidden">5</li>
<li class="hidden">6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
<li>11</li>
</ul>
I want to list displaying on the browser should have alternative color irrespective of the number of hidden children.
jQuery selector is described in the Selectors/nthChild docs, and the above can be accomplished with $("li. mybutton:nth-child(2)"). hide() .
In order for the nth-child rules you've declared to work after a user clicks to hide divs, you need to remove the hidden divs from the DOM, so they no longer exist as siblings. In your question you request a CSS-only solution.
formula (an + b) nth-child(3n) would affect every third child element. nth-child(3n+1) would apply to every third element starting from the first one.
If you could change your document's structure, then you could set a different tag for the hidden items, so that you could take advantage of the :nth-of-type
pseudo-class:
CSS:
div.list p {
height: 2em;
border: 1px solid black;
margin: 0;
}
div.list p:nth-of-type(odd) {
background: khaki;
}
div.list p:nth-of-type(even) {
background: indianred;
}
.hidden {
display: none;
}
HTML:
<div class="list">
<p>1</p>
<p>2</p>
<p>3</p>
<span class="hidden">4</span>
<span class="hidden">5</span>
<span class="hidden">6</span>
<p>7</p>
<p>8</p>
<p>9</p>
<p>10</p>
<p>11</p>
</div>
As this answer explains there is currently no way to do this purely with CSS. You could work around this by altering the code that hides the li
elements so that it inserts a another hidden dummy element after the hidden item to even things out and make it look right, and then remove that dummy item when you un-hide it.
var hide = function (el) {
el.classList.add('hidden');
el.insertAdjacentHTML('afterend', '<li class="hidden dummy"></li>');
},
show = function (el) {
if (el.classList.contains('hidden')) {
el.classList.remove('hidden');
el.parentNode.removeChild(el.nextElementSibling);
}
};
Working fiddle here
You will need to remove the hidden elements from the DOM, rather than just hide them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With