Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a proper and wrong way to format CSS?

When I first started writing CSS, I was writing it in an expanded form

div.class {
    margin:      10px 5px 3px;
    border:      1px solid #333;
    font-weight: bold;
    }
    .class .subclass {
        text-align:right;
        }

but now I find myself writing css like this: (Example from code I'm actually writing now)

.object1 {}
    .scrollButton{width:44px;height:135px;}
        .scrollButton img {padding:51px 0 0 23px;}
.object2 {width:165px;height:94px;margin:15px 0 0 23px;padding:15px 0 0 10px;background:#fff;}
    .featuredObject .symbol{line-height:30px; padding-top:6px;}
    .featuredObject .value {width:90px;}
        .featuredObject .valueChange {padding:5px 0 0 0;}
        .featuredObject img {position:absolute;margin:32px 0 0 107px;}

and I'm beginning to worry because a lot of the time I see the first form done in examples online, while I find the second form a lot easier for me to work with. It has a lower vertical height, so I can see all the classes at a glance with less scrolling, the tabulation of the hierarchy seems more apparent, and it looks more like code I'd write with javascript or html. Is this a valid way of doing code, or to keep with standards when putting it online should I use the vertical form instead?

like image 285
DavidR Avatar asked May 28 '10 17:05

DavidR


3 Answers

Well, here is what say the most :)

summary: css-tricks.com ran a poll. By a margin of roughly 3 to 1, most people preferred multi-line over single line css styles.

like image 200
Sarfraz Avatar answered Oct 16 '22 15:10

Sarfraz


I personally prefer the first style. I like things that are easy to read and I don't mind scrolling. The dense nature of the second style slows down my reading, my ability to pick out the items that I'm interested in.

There certainly are trade offs to be considered with CSS due to the file size. CSS can be compressed. I find the size of CSS files to be the least of my worries with the sites I've built so far.

Ultimately, the important thing is that whichever style you choose to use is to be consistent. That consistency will make your life simpler when you have to update your CSS or when another developer has to update your CSS.

like image 38
Mike Chess Avatar answered Oct 16 '22 15:10

Mike Chess


Indicating the hierarchy using indentation is not a bad idea. However, you should be careful that you don't fool yourself. In your example, you may be assuming that .scrollButton is always within .object1. But CSS doesn't obey that rule. If you used a .scrollButton class outside of .object1, it would still get the styles.

like image 5
JW. Avatar answered Oct 16 '22 16:10

JW.