user1915190
user1915190

Reputation: 307

Which is the best way to code CSS

I have so many blocks with different sizing, padding and margin values. So I thought to create support CSS classes and combine as below;

CSS

.m-t-5 { margin-top: 5px; }
.m-t-10 { margin-top: 10px; }
.m-t-15 { margin-top: 15px; }

p-10 { padding: 10px; }
p-15 { padding: 15px; }

.f-left { float: left; }
.f-right { float: left; }

HTML

<div class="m-t-5 p-20 f-left lined"></div>
<div class="p-10 m-0 f-right"></div>

By using this all my class names are becoming big(I mean in length). So is this a good practice? please suggest me wether to continue this way or creating multiple CSS classes with its own properties.

Regards.

Upvotes: 4

Views: 335

Answers (4)

mknayab
mknayab

Reputation: 302

I agree with @ryan, but you also need to be tricky and intelligently move around as-per your layout to reduce the code as maximum as you can. And also avoid using (-)&(_) etc... and make very simple & clean naming conventions. Please see example below:

CSS

.mt5 {margin-top: 5px;}
.pd5 {padding: 5px;}
/* Margin Top 5 and Padding 5 */
.mt5pd5 {margin-top: 5px; padding: 5px;}

.fl {float: left;}
.fr {float: right;}

HTML Markup

<div class="fl mt5 pd5">Welcome</div>
<div class="fl mt5pd5">Hello</div>

Upvotes: 1

Ryan
Ryan

Reputation: 5682

Two things:

This is perfectly fine and is very common. It actually helps to keep the DRY principle.

Second: The only 'best-practice' for coding css is to avoid inline css, but even that has exceptions. So if it works for you then go ahead and use it. (But again what your doing is considered ok practice.)

Upvotes: 1

Rohit Azad Malik
Rohit Azad Malik

Reputation: 32182

now used to this way

as like this

.marginT10{margin-top:10px;}
.marginT20{margin-top:20px;}
.marginT30{margin-top:30px;}
.marginT40{margin-top:40px;}
.pull-left{float:left;}
.pull-right{float:right;}

Upvotes: 1

jokeyrhyme
jokeyrhyme

Reputation: 3638

There are a few methodologies that suggest advice here:

There's also the HTML/CSS style guide that Google's own developers adhere to.

Upvotes: 3

Related Questions