Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add CSS if element has more than one child?

Tags:

html

css

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?

like image 879
user348173 Avatar asked Sep 11 '13 09:09

user348173


People also ask

How do I add a multiple nth child in 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.

How do you apply CSS to all child elements except first?

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.

Can CSS be used to find child => parent page 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.


2 Answers

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; } 
like image 195
Michael Low Avatar answered Sep 20 '22 06:09

Michael Low


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> 

CSS

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

like image 45
Danield Avatar answered Sep 21 '22 06:09

Danield