I have td
tags and a several div
inside td
:
<td> <div class='test'></div> <div class='test'></div> </td> <td> <div class='test'></div> </td>
I want to add margin-bottom
to div
if there are more than one in the td
. How can I do this with the css?
The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.
This selector is used to select every element which is not the first-child of its parent element. It is represented as an argument in the form of :not(first-child) element.
There is currently no way to select the parent of an element in CSS, at least not a way that works across all browsers.
You can't directly 'count' total numbers of elements in CSS, so there's no way to only apply the class if there's 2 or more divs (you'd need JavaScript for that).
But a possible workaround is to apply the class to all divs in the td...
td > div { margin-bottom: 10px; }
... and then override/disable it with a different style when there's only one element. That indirectly lets you add the style when there's 2+ more child elements.
td > div:only-child { margin-bottom: 0px; }
Alternatively you can apply to every div after the first one, if that happens to work for your situation.
td > div:not(:first-child) { margin-bottom: 10px; }
Edit: Or as Itay says in the comment, use a sibling selector
td > div + div { margin-bottom: 10px; }
Well actually you can do this with css using the nth-last-child
selector
FIDDLE
So if your markup was like this:
<table> <td> <div class='test'>test</div> <div class='test'>test</div> </td> </table> <hr /> <table> <td> <div class='test'>test</div> </td> </table>
div:nth-last-child(n+2) ~ div:last-child{ margin-bottom: 40px; }
... the above css will style the last div element only if there exists a container that has at least 2 child divs
Just to see how this works better - here's another example fiddle
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