Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this CSS usage valid for targeting nested divs?

basically just want to know if the attached image shows a valid CSS usage? I'm using a lot of nested divs lately and this is how I'm targeting them in my CSS. It works really well but I'm just curious if it's a good way of doing it? Or is there an easier / more efficient way?

Thanks!

Illustrationlink to the image

like image 463
Ben Clarke Avatar asked Sep 30 '22 16:09

Ben Clarke


2 Answers

First of all: yor way is totally ok and the efficiency depends on the whole page. Maybe it can get more efficient with those ideas:

If your div-classes or ids are unique

You can also write just the class - you dont have to write the whole path then. Instead of

#content > .inner > .content > div { }

it is possible to write for example

.content > div { }

Helpful when you are using nested divs

When using nested divs you very often have to type a lot of code multiple times:

#content > .inner > .content { }
#content > .inner > .content > div {}
#content > .inner > .footer {}
#content > .inner > .footer > div {}

There are very helpful scripts called LESS and SASS (both of them work pretty much the same). They allow you to write everything just one time like

#content {
   .inner {
      .content {
         // some stuff
         div {
            // some stuff
         }
      }
      .footer {
         //some stuff
         div {
            // some stuff
         }
      }
   }
}
like image 150
Jere Avatar answered Nov 15 '22 13:11

Jere


The direct child selector (ie. > ) is fine, but personally I don't like it because it makes it difficult to move and re-use styles. For example if I want to use .content somewhere other than #container I'm going to have to change a whole heap of CSS. Ideally you should be able to re-use blocks of markup without having to change CSS.

The direct child selector is best used to limit the depth to which a style is applied. For example it would be appropriate to use .content > p if you want the style to apply only to direct children so you can have another style for deeper children. If that's not the case then you might as well just use well named class and ID selectors.

like image 43
thexacre Avatar answered Nov 15 '22 12:11

thexacre