January 14, 2012

Better way to select a child menu item selector in CSS

Question by CodeDevelopr

I found this amazing resource http://gtmetrix.com/ that you supply a URL to a website and it gives you a performance report and gives you estimates on what you can save by compressing and optimizing different things.

It even does most of it for you, it optimized all my images, css, and javascript files, showed me css that is not being used on the current page, it also shows a list of non-efficient CSS selectors and shows the selector and the line number it is on in your css file.

Here is one of the results for me that I use for a navigation menu

ul#menu-navigation li>ul li a Tag key with 3 descendant selectors and ID overly qualified with tag
ul#menu-navigation li>ul li a:hover Tag key with 3 descendant selectors and ID overly qualified with tag

So my question is, is there a better way to do a UL list menu that has sub-menus items?

Answer by Mohamed Meligy

First, you don’t need the ul before the ID, because the ID is unique enough, but it’s arguable for readability for you, etc..

Of course also you can remove the >ul, but I assume you added it consciously to be specific, and in CSS, it’s “safer” (while “better” is arguable) to be more specific than generic.

Then, assuming you don’t change your markup (with extra class or so), I think this is the right way. There is redundancy and such I completely agree. This is an inherited problem in CSS. You can’t solve it with CSS itself. You live with it, or you look for something that doesn’t have the problem to generate CSS for you.

In my current project, I’m using LESS CSS, this is a syntax very similar to CSS, and generates actual CSS files via a command prompt (or a Visual Studio extension called, well, LessExtension, which generates on save). There is also JS file for generation in the browser.

Check it out. I bet you’ll like it. You can take your CSS file as is, and start adding benefits.

http://lesscss.org

You selectors in LESS would be:

#menu-navigation {
    li>ul li a {
        /* some Anchor styles */

        &:hover {
            /* some Anchor hover styles */
        }
    }
}

Of course you can also have middle nesting levels as well. Here I did all li>ul li a one selector instead of multiple nesting levels for simplicity, but normally I’d make each of them a nesting level.

Answer by Starx

Since your css is for the anchor tag. Your selector can be brought down to

  1. Generalised Anhor #menu-navigation li a
  2. Speciliazed Anchor inside list #menu-navigation li > ul li a

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!