CSS Style

Why do we write CSS code this way(1)? if it takes so much space instead of this (2) which still makes the code work looks better and it takes way less space? please some expert answer this for me thanks.
(1)p {

color: green;

}

h1 {

color: maroon;

}

(2)
p {color: green;}
h1 {color: maroon;}

This is the link of the exercise i am in.
https://www.codecademy.com/courses/learn-css/lessons/learn-css-selectors/exercises/type

Hey there, welcome to the forums!

It’s a mix of personal preference and also good practise. In your current situation naturally with only one element it looks a bit wasteful. However imagine you have multiple properties you want to apply, for example for my personal site, I am creating a mobile friendly hamburger menu. Here is what my CSS for the nav menu looks like;

#hamburger-nav-list {
    display: inline-block;
    list-style: none;
    margin: 0;
    padding: 0 10px 0 0;
    max-height: 0;
    overflow: hidden;
    position: fixed;
    width: 99%;
    background-color: #579ED9;
    border-bottom-left-radius: 20px;
    border-bottom-right-radius: 20px;
    transition: max-height 0.3s ease-out;
    z-index: 10;
}

It’s easy to distinguish different properties, what they are and what their values are etc. Now here is the inline version like you have;

#hamburger-nav-list {display: inline-block;list-style: none;margin: 0;padding: 0 10px 0 0;max-height: 0;overflow: hidden;position: fixed;width: 99%;background-color: #579ED9;border-bottom-left-radius: 20px;border-bottom-right-radius: 20px;transition: max-height 0.3s ease-out;z-index: 10;}

We can see it is much more annoying to go in and easily locate a specific property to change. We have to scroll a lot, and also it’s a lot harder to see problems, for example a missed semi-colon or wrong number. However the actual code is fine in this case and the website reads both with no problem whatsoever.

In your scenario, it can look nicer and more compact with one single property. However on the whole, whitespace and line breaks are really useful for readability and debugging errors, especially in CSS where one wrong word or number can entirely change the look of the site. There’s also no real necessity for the extra line-breaks, as you can see in mine I don’t have one before and after each curly bracket, that’s where personal preference comes into it.

3 Likes

Great info. I am new to the forum. Thanks for sharing.

1 Like

Thanks for taking your time and explaining this for me now that i am way more deep into the css course i can see why we do it the way we do it just like you explained.