Need help on CSS

Hi,

I have a big disadvantage in understanding CSS and I want to learn how to use it in the best way.

Lets assume I have a simple page with header, content and footer sections like this

body
{
    font-family: Arial, serif;
    color: blue;
    background: red;

    .header
    {
        position: absolute;
        left: 0;
        right: 0:
        top: 0;
        height: 2rem;
        padding: 10px 10px 10px 10px;
    }
    .content
    {
        position: absolute;
        left: 0;
        right: 0;
        top: 2rem;
        bottom: 2rem;
    }
    .footer
    {
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        height: 2rem;
    }

<body>
    <div class = "header"></div>
    <div class = "content"></div>
    <div class = "footer"></div>
</body>

Now I want to show another div in the content div which has the same structure.

<body>
    <div class = "header"></div>
    <div class = "content">
           <div class = "new">
                  <div class = "header"></div>
                  <div class = "content"></div>
                  <div class = "footer"></div>
           </div>
    </div>
    <div class = "footer"></div>
</body>

my understanding normally is that when I now define

body .content .new .header
{
    .....
}

the header div in the new div should get this and only this style attributes. But in real world it is also getting the attributes from body .header
How can I change this to not have this attributes in my new .header but have the header inherit from body .content only but not from body .footer?

Sorry Thallius, me again.

It’s in the name e.g. ‘cascade’, styles cascade down.

The reason to have the same name is that you do want to share some styles.

In your example, you could use semantic html5 tags instead.

<header class='top_header'></header>
<main class='content'>
  <header class='content_header'></header>
  <section class='content_body'></section> <!-- main just felt wrong here for some reason-->
  <footer class='content_footer'></footer>
</main>
<footer></footer>

This would enable you to add element specific styles more easily. It would also give you the hooks to select multiple headers and footers.

For some reason I couldn’t bring myself to add another main, but maybe that’s alright too.

Just my take.

edit: There are multiple ways to do this obviously. You could have an id and class name, if it is unique e.g. #top-header.header or there are pseudo selectors like :not, but the above seems simpler to me.

3 Likes

I thought there is a way to reduce the scope so I must not give unique class names.

Of course I can do like this

<div class = „main“>
     <div class = „mainHeader“>
     <div class = „mainContent“>
          <div class =„child“>
                <div class = „childHeader“>
….
</div>

But for me it’s some kind of superfluous to give the parents class name in all subclass names.

I guess one way is you could use a child combinator to select only the direct children of the parent

body > .header {
  ... styles here
}

If I am correct, this would not apply to more deeply nested .header elements.

1 Like

Ok,

that’s more the other way around but its a start. So if I define

body > .footer

the .footer is not found in any other child of body.

1 Like

Here I had to check :slight_smile:

1 Like

Please don’t do that. :slight_smile:

Do this instead


.header{styles here ..}
.subheader{styles here}

Keep it simple and don’t fight the cascade. Use it to your advantage

Keep your selectors short and don’t be afraid to add extra simple classes when you need something different.

Try not to undo styles as that implies you haven’t thought the process through fully.

3 Likes

So if you see yourself reaching for !important take a step back and take stock of the big picture and what you’re missing in it.

As for structuring CSS I would suggest looking into known methods such as BEM

2 Likes

So if that is true, why should I use CSS enhancements like SCSS or SASS?
Because this is exactly what they are doing when you create structures like

.header
{
    color : red;

    .logo
    {
        color : green;
    }
}

And that’s what for me as a programmer makes sense. I could easily define the scope of a class to a parent class if it would work like I was expecting. But as I said. It doesn‘t. So for me this notation is completely useless

Yes and that’s why I dislike them and never use them unless forced to. :slight_smile:

I see no benefit and only drawbacks in that method. You get long selectors and unwieldy styles leading to spaghetti code. Not to mention that it makes reading the code much harder. You have to keep looking back up to see if you are still within a parent selector and that makes maintenance and debugging a pain.

Yes and that’s the problem with programmers as they are always trying to relate css to programming and miss the bigger picture. :slight_smile:

Css needs a different approach where you work with the cascade and are not trying to program every little thing. It’s a different mindset to programming and indeed many programmers have the same issues you mention because they want fine control over everything.

I see little benefit in css pre-processors these days except for fancy demos where you want to loop through hundreds of things.

I’m not sure if you can access this article on medium but it’s a good read.

My basic approach is to keep my selectors as short as possible and not to be afraid to add classes where needed. It makes life so much easier and more manageable.

As soon as you say something like div > p.test you then tightly couple your css to that structure. If later on you decide the div should have been another element then your rule fails. If you had just said .test then it works forever (within reason). There are exceptions to the rule but generally most of your rules can be simple selectors.

5 Likes

Hi Paul,

thanks for your point of view.

This is a nice idea but it also takes the big risk to have double styles for different things if you work in a big team.
Also my apps are loading all content dynamically. I don’t like it when I reach out to a web application and its telling me “Loading” for 30s until it has loaded all its content of which I might only need 5%.
So my software is loading content on demand.
That means, if the user clicks on a button, which opens a new functionality, I load the HTML, CSS, JS and Localized Strings from the Server for this module.
So in my case I need to have unique names of the styles to be sure to have no change in a loaded CSS override one already loaded only because I have named them equal.
To do so I could of course start all class names with the module name.
Lets say I load a module which is for user management. here I get a div which contains the user list and if I click on a user in the list I get a div in which I can edit the users details.
So all my classes in the user list div I need to call

.userList
{
}
.userListTitle
{
}
.userListTitleText
{
}
.userListSubTitle....

.userDetails
{
}
.userDetailsTitle
{
}
.userDetailsTitleText
{
}
...

Now all this userList and userDetails repeating again and again and again. That is not good for my personal Monk :slight_smile:

So it would be much smarter to say

.userList
{
    .title
    {
        .text
       {
       }
    }
}

Don’t you agree?

1 Like

Edit: Sorry @rpkamp, should have read the last sentence of your post. So re-worded.

Here is a short video on BEM for your consideration @Thallius

I have got back into using Sass recently and quite like the nested structures, it feels modular to me. That said it maybe a combination of novelty and ignorance on my part.

1 Like

Cheers :). That’s a good point to remember as this is only my preference but is based on 20 years of CSS. Others may see it differently.

Indeed in the first 5 years of css I avoided using classes as much as possible and could style whole pages based on the html (or the zen garden approach). That approach soon failed when I started working for clients and they’d change one line of html and the whole thing broke.

I now try to write code that still works should the html change or if the client adds another paragraph of text or inserts an image somewhere I didn’t expect. You can’t plan for everything but you can plan for something.

No that’s three rules instead of one :slight_smile:

What’s wrong with just .text ? (apart from its name)

Your code compiles to .userlist .title .text{}. That raises the specificity three times and means the UA has to work three times as hard to find and implement those rules. It’s seldom an issue with a fast machine but on a large application with lots of those rules you could end up getting a lag in some extreme cases.

That doesn’t alleviate the problem. Your team could still create .userlist somewhere else and break the rules.

If you named the classes more aptly then the issue is reduced also I don’t mind perhaps one level of nesting but it does pain me to do it :).

Unless it’s a mammoth application I don’t like the module approach (unless it’s just a few well chosen modules).

In most normal sites your total css files should be under 80k anyway. Why not get rid of one small image instead :slight_smile: in that way your css is ready to go from anywhere as it’s cached and available.

Most of the problems I see is that developers are loading library after library to do the most simple thing in css. Framework libraries, animation libraries and so on. As a programmer you’d be the first one to say “why are you using jquery” when vanilla js can do most of it now. :slight_smile:

I have worked in a large project for about 5 years where there were about 10 people working on the application and they were using the module approach. It was written in angular of which I know nothing but they wanted me to write the css for each module.

As the scope was limited to each module it ended up with so much duplication of code that it seemed slightly pointless to me. If someone then decided to change the theme or design you had to change all the modules! One or two main css files would have sufficed.

The trouble is that when you let programmers take over the css you no longer get css:)

Of course there is a time and place for everything but when you only have a hammer then everything looks like a nail :slight_smile:

I’m not saying you can’t use the methods you mentioned but I would say use them with care. Read the article I mentioned above as it echoes a lot of my thoughts.

2 Likes

That’s the crux of the problem right there :).

CSS was never meant to be modular. That’s why it was called Cascading Style Sheets :slight_smile:

Shove a piece of html in your page and it picks up the styles from that page. Perfect:)

I know I’m being simplistic but my mind works differently. I tend not to think in terms of nesting or modules. I see dead people elements inserting pressure and influence on other elements. I style what needs to be styled rely on the cascade as much as possible.

In the end it does end up being a personal decision but I do hate these monolithic frameworks that won’t even load on my half a mbyte connection. :;

2 Likes

Of course I can put everything in one big CSS file, but then reusing a module in another project is a pain in the ass because I have to take care that I copy the right styles from one css to the one css of the new project. Much more easy if the module itself is taking care of everything it needs.

1 Like

So how about a middle ground. A mix of BEM and Sass, but limited to only one level of nesting — sorry if I am still missing the point.

So for example

<nav class='nav'>
    <ul class='nav__list'>
        <li class='nav_item'>
            <a href='' class='nav__link'>Home</a>
        </li>
        <li class='nav_item'>
            <a href='' class='nav__link'>About us</a>
        </li>
        <li class='nav_item'>
            <a href='' class='nav__link nav__link--active'>Help</a>
        </li>
    </ul>
</nav>

Then for the Sass

Edit: I see them too :biggrin:

1 Like

Maybe the problem is, that CSS has more and more become relevant for not only design (What for me is Colors, Borders, Fonts) but also for the Architecture (DIV positions, sizes etc)

So for the design part I am totally with you, that this should be part of one global CSS which is giving the look and feel to all modules.
But the architecture part is clearly only depending on the module itself and never used elsewhere. And this is what I am talking about.

1 Like

That’s better as there is less specificity but from my point of view I still see that .nav_item does the job on its own.

Are you going to have nav-items all over the page? If the answer is yes then that’s a red flag to me. If I have another navigation perhaps in the footer then it would be called something else unless it used all the previous rules without modification (or little modification as I try to avoid undoing styles).

I understand where you are coming from and I can see use cases for this but I would rarely expect a module to look vastly different from the current theme so once again you are just styling the differences.

There is of course a case for having completely isolated elements where you have reusable components that you just want to drop in somewhere. There are already drafts in the css spec to isolate the code from the cascade and let the element just use its own subset of css.

My issue is that once you do this you lose the fine control from the main style sheet and need to look into various different modules just to change for example the font. Is it any better than when in 1999 we could just write <span COLOR=“red”>Warning</span>

In large applications I can see the need to be a bit more modular but when I reach those large sites on my slow connection they tend to freeze so that approach is not working for me.

Even if your application is modular it still pays to make your css as succinct as it needs to be.

It’s like no matter how much ram you have on your computer it always seems to get full up with junk :slight_smile:

3 Likes

This is the part I keep coming back to. Modules that look vastly different in look and feel to each other will be jarring to users, and pixel perfection in browsers is an exercise in futility (or insanity, depending on how you look at it).

Finding commonalities and coding for them in one place, and only THEN coding for those things that are different is less work in the long run

3 Likes

I don’t think you understand me right.

All modules will have the same look if they share the same Colors, Borders, Fonts etc. But each module has a completely different architecture of divs.
For example one module only needs 1 div with some text inside. the next needs 5 divs and in each div are 3 other div and they all contain different text content, buttons etc.
In the very old past I would have created a div

<diiv width = "300px" height = "200px">

Today I create a class for this with not absolute sizes to make it able to resize on content.

So all this div styles are really only used for this module. I can never use this for another module as it contains module specific stuff. It makes absolutely no sense to put this in a big global CSS file.

1 Like