3

I have an element that may contain 1, 2 or 3 subelements:

<div class="wrapper">
  <div class="element" />
</div>

or...

<div class="wrapper">
  <div class="element" />
  <div class="element" />
</div>

or...

<div class="wrapper">
  <div class="element" />
  <div class="element" />
  <div class="element" />
</div>

I want to apply styles to .element depending on how many siblings there are.

For example, something like...

.wrapper .element {
width: 50%;
}

.wrapper .element:only-child {
width: 75%;
}

...but I cannot figure out how to differentiate between the 2 elements and the 3 elements. Is this possible in pure css?

Thanks ( in advance ) for your help.

PHPSrike
  • 33
  • 1
  • 9
user1031947
  • 6,294
  • 16
  • 55
  • 88
  • 1
    There's no pure-CSS solution to this (so far as I'm aware), as yet. However it could be done with some HTML-changes, or with JavaScript. – David Thomas May 31 '13 at 18:37
  • Use `jQuery` if you don't want to add `data-` attribute if the number of sub-elements change frequently – Sourabh May 31 '13 at 18:37

1 Answers1

1

This is actually pretty easy to do, usually people use the data attribute [thanks @david-thomas] in html to accomplish this:

A DIV wrapper and children:

<div class="wrapper" data-wrapper-subs="3">
    <div class="some-class">Child 1</div>
    <div class="some-class">Child 2</div>
    <div class="some-class">Child 3</div>
</div>

And its CSS:

div.wrapper[data-wrapper-subs="1"] div { width: 99%; }
div.wrapper[data-wrapper-subs="2"] div { width: 49%; }
div.wrapper[data-wrapper-subs="3"] div { width: 32%; }
div.wrapper[data-wrapper-subs="4"] div { width: 24%; }
div.wrapper[data-wrapper-subs="5"] div { width: 19%; }

div.wrapper div.some-class { /* Generic child styling */ }

The important thing is to set the data-wrapper-subs to the number of children.

If you don't know the number of children obviously this won't work, but as far as I know you can only style based on :first-child, :last-child, :only-child, :nth-child(odd), :nth-child(even) and :nth-child([number])

siva.k
  • 1,344
  • 14
  • 24
  • A touch of JS to dynamically add the data-element would solve the issue of not knowing how many children there are before hand – Dre May 31 '13 at 19:12
  • 2
    `data-*` is an *attribute* of an element, not an element itself. =) – David Thomas May 31 '13 at 22:09
  • @Dre you can do it using JS, yes, I tend to shy away from solutions that require JS for proper viewing though as people with it turned off may get an unusable view. – siva.k Jun 01 '13 at 00:07
  • @david-thomas I agree; I would also ensure that there are relevant fallback styles in place to ensure that it was viewable (for example defaulting all widths to 100%). I must avoid leaving overly concise comments! In a real-world scenario I would shy away from this kind of layout; it – Dre Jun 03 '13 at 16:31