css – Do nested selectors affect website loading speed?

Question:

There is sass:

#header {
    @include position(fixed, 0 null null 0);
    width: 326px;
    height: 100%;
    background-color: #1F1916;
    text-align: center;

    .top {
        @include position(absolute, 0 null null 0);
        width: 100%;

        .logo {
            background-color: #fff;
            display: block;
            padding: 50px 0 44px;

            img {
                width: 185px;
                height: 71px;
            }
        }
    }

    .bottom {
        @include position(absolute, null null 0 0);
        width: 100%;
    }
}

As a result:

#header .top .logo img {}

Does this affect anything, if so, in which direction?

Answer:

#header .top .logo img {}

  1. The browser reads selectors from right to left. Those. the browser will select all the images, then it will find out which they have a parent with the .logo class, then with the .top class … Well, you get the idea.

Now, browsers are pretty smart, but still: it would be more reasonable to set a separate class for a specific element (picture in your case), for example, .header_logo_img .

  1. Using id in css is not cool. And such selectors like #header .top .logo img – have a very large "weight". It will be difficult to "interrupt" them in the cascade of styles below.

I advise you to read about methods of writing classes, for example, BEM. And also install a linter, for example, SCSS-Lint.

Scroll to Top