Sometimes we try to write the CSS Style Sheet with the less lines possible.
Let's look at this example:
Note: Previously borders where all width:1px, border-style:solid and border-color:#000
Scenario:
We want to change:
the width of: R, L and B to 0px
the border-color of: T to #ddd
Code Used:
border:0 solid #ddd;
border-top-width:1px;
What did the code above did unnecessarily?:
changing the border-color of: R, L and B (3 actions)
changing the width of: T (1 action)
Here is the code with 0 unnecessary actions:
border-right-width:0;
border-bottom-width:0;
border-left-width:0;
border-top-color:#ddd;
The question is: should we sacrifice efficiency for less-code/readability?
The efficiency loss will not be measurable, if any.
It is always better to write well readable code.
And in the end you first example's file size is less, so downloading the CSS is quicker.
should we sacrifice efficiency for less-code/readability?
Yes! If you want efficiency, compress your code, but always have a fully readable, easy to modify, clear and to-the-point, source version.
And it's usually best to have zero inline styles. If it's just one element, give it an id and put the style for it in your CSS file.
In my opinion, rewriting CSS is part of CSS.
As for efficiency, I don't think you will notice a measurable difference (with the exception of download times) in between the two.
What is important is to be consistent, and make your code readable.
As for your example, I would have done:
border:none;
border-top:1px solid #ddd;
Simply because I feel that makes it more readable
I think you're asking the wrong question. The sample you provided is not going to result in much of a difference at all between download-times or the time it takes to render the page. I think any web-developer's main focus should be on making the code easily readable to at least themselves, and preferably to others.
I would have done this:
border-width: 1px 0 0 0;
border-style: solid; /* may not be necessary as many browsers use this as default */
border-top-color: #DDD;
It's short, and not very cryptic as to what the display is like, and doesn't do anything unnecessary.
As for compression: not sure what the authors meant by it but if you minify the code, the browser at the other end won't "unminify" it to read it like we would want to. Empty space is ignored anyway, and if not there, that probably even speeds up the parsing...
Related
I am finding myself constantly reusing various blocks of code in CSS for various elements. One is rounded corners. Example code below:
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
-khtml-border-radius: 10px;
border-radius: 10px;
I've tried 2 different methods to reduce code repetition, which both have cons.
The first is to wrap the code in a class such as .rounded10 and add this class to all the elements on the page that require rounded borders (there's a good 20+). Bootstrap do something similar, but I don't like this method as it introduces unsemantic data into the HTML.
The second is to create a list of elements in CSS that should have rounded borders like:
.offers, .welcome, .sidebar, .post {
... Rounded corners code here ...
}
I'm not sure if this method is even used, I've not seen it.
Are there any other method's I've missed or anything that can help me reduce this repetition in such circumstances. Things get messy especially when you have to use browser vendor properties.
I do not use SASS or LESS, or any CSS frameworks, or helpers such as Compass (although I have). I preferrer to code with vanilla CSS. It's just the way I work. Please no suggestions on using those.
Other than giving classes for certain features of that element and avoiding a CSS preprocessor there isn't much else you can do.
If you are finding yourself having about 20 odd classes for rounded corner sizes then you should question the consistency of your designs.
There are some great articles on HTML and CSS semantics such as http://nicolasgallagher.com/about-html-semantics-front-end-architecture/ .
I'm not going to suggest you use something like SASS or LESS but I strongly recommend you do so. It will allow you to easily add rounded corner classes and save you time in outputting compressed formats of your CSS.
One way to trim down css is to use better selectors. For example if you need to have all div in your menu block to have a background colour you could have:
#menu div
{
background-colour:red;
}
See CSS selectors at Sitepoint for a good refrence.
Say throughout my site, there is multiple places that I want my text to be coloured #f00
If I want to target them, should I make one declaration to target everything at once e.g.
a, .color, h2 {
color: #f00
}
OR, should I "color" them when I am targeting them anyway e.g.
a {
padding: 5px;
color: #f00;
}
.color {
background: #333;
color: #f00;
}
h2 {
font-size: 20px;
color: #f00;
}
I'm never sure which to do, sure, the first part in this isntance looks like less code, but then I am referencing tags more than I need to. But on the other hand, I am using color: #f00 3 times instead of just the once.
I appreciate neither are "wrong", I was just wondering if one is quicker, more semantic or what.
Note: This isn't my code in any site, just a quick mock up. I'm looking for an answer on a bigger scale
The first one is the preferred method. Typically, a developer's goal is to minimize CSS size to encourage faster loading. Your first example surely takes up less space as a result of combining the classes together.
I think this is mostly a stylistic choice, but I'll tell how I approach it.
If there's something all these cases have in common that implies that they should always have the same color, then group them together.
However, if there's something they have in common, that suggests that you should perhaps give that commonality a name, and make it a class name. Then assign the style to the class. This is good modularity.
If it's just by chance that they have the same color, and you're likely to change one without changing the others, use the second form.
Hope's answers is true, but unless there are a huge number of styles like this I doubt that it's going to have a noticeable impact on loading time.
I haven't played with LESS yet, I wonder if it optimizes this automatically.
The first option should be the best, in the sense that if you write less code, and that if you wanna change this color into another one everywhere, you'll have a single line to change.
But finally, this is more useful to use the second method.
If you still wanna change this color everywhere, event the simpliest editor will allow you to do it easily. But if you wanna change the color of a single div, you'll need to move your code.
A good practice (using the second method), is to reference all used colors at the top of your main css file (in comments), then you can easily pick one to search/replace all matches.
I am wondering which one out of the CSS rules below renders faster:
#avriable_info table td {width: 250px; font-size: 13px;}
or
#avriable_info table td {
width: 250px;
font-size: 13px;
}
Neither one will be "faster" to render than the other because most parsers will normalize a file before parsing. e.g. Getting rid of white spaces and new lines and such.
Now, if you have a huge file that isn't being gzipped across the wire then the first one will download faster to the client than the second one which will allow the browser to start rendering it before the larger, slower one.
Neither will make any noticeable difference. A couple of newlines in your CSS is gong to make no more than a few CPU instructions difference to the rendering.
Maybe if you had a million lines of CSS you might notice a millisecond's difference, but if you're optimising that much (especially on a webpage!) you have far more serious issues to worry about (and they're not code related! ;-)).
The difference is two line breaks. This difference is eliminated by the parsing of the file and is unnoticable compared to the parse time of the 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?
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.
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.
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.
I dont know about you but I like the vertical mode during dev as it is far more easier to read for me.
However, in prod, you wanna compress your css to reduce payload and hence, the second style makes sense. Mostly, you would be using some CSS compressor to do this.
i like to write css in multi line. because this is easier to write and read. we can find error as early as possible and a look of view is nice with indentation . mostly when a designer work with css and gave to developer to develop site than developer can understand easily.
so i think multi line css is better way to work.
I personally find both of your examples hard to read, especially the second one.
Multi-line is easier to follow, and indentation can be misleading as CSS is not necessarily applied in that way. Your indentation may lead you to believe it is.
I prefer the basic tried and true method of multi-line, with reasonable/logical order:
div.class
{
margin: 10px 5px 3px;
border: 1px solid #333;
font-weight: bold;
}
.class
{
text-align: center;
margin-left: 10px;
}
.class .subclass
{
text-align:right;
}
Takes up a little more space and requires a little scrolling to take in, but is easy to follow. Those worried about optimization can always use CSS shrinking tools for production CSS files.
In the end as long as you are very consistent with your work and across a team (if applicable) then no answer is more correct.
I prefer the second style, but be aware that it's a style. In the same way that some people prefer
function (arg)
{
body();
}
to
function(arg){
body();
}
I don't get it, myself. The argument is "it's easier to read", and my response is consistently "... for you". As a note, I get the feeling that this is why so many examples use the more-whitespace version; it has the reputation (if not confirmed property) of being easier to read.
Pick the one you like and stick with it. If you have a team to cooperate with, try to get to consensus, or barring that, write some auto-formatting scripts and stay out of each other's way. It's not like it's terribly difficult to mechanically transform one into the other.
The style you write in is your choice(I prefer multi line) but as Rajat said you want to remove any extra whitespace after dev. Anytime you can reduce file size and payload you are doing your site and your visitors a favor.
I think it also depends on your editor. I use multi line formatting and condense every definition with Vim's folding (I set up folding marks to be { and }) so I get one tag/class/id per line, expandable when needed.
Using comments to identify "sections" I get a very clean look with minimal vertical scroll while maintaining the readability of multi line on expanded definitions.
I just want to point out that Textmate has an option that allows you to easily switch between these two styles by selecting an area and pressing Ctrl-Q/Ctrl-Alt-Q to expand/collapse. As a consequence I have come to find that I prefer my CSS collapsed unless I am writing or deep debugging a specific section. But, with the ability to easily switch between he two I see that both ways are useful for different circumstances.
I prefer multiline right up until we deploy. At that point I want it minified.
Perhaps, when you have multiple selectors and one rule, like this:
#header li a, #header li span {
display:inline-block;
}
So, I prefer to do:
#header li a,
#header li span {
display:inline-block;
}
I've always liked this style:
#something1 {
color : #ffffff;
background : #000000;
}
#something2 {
color : #000000;
background : #ffffff;
}
But yo answer your question: As long as it functions the same way, there is no "proper" or "best" way to format your code. Use a style your comfortable with.
In CSS2 and even in the upcoming CSS3, I can't find something that would be completely natural and time-saving - applying CSS styles from within other styles, rather than from HTML.
For example:
.awesome-image {
border: 1px #000 solid;
margin: 2px;
}
.super-awesome-image {
.alwesome-image; // or something like that - this is similar to a function call in a functional language
padding: 2px;
}
Oftentimes, one doesn't have access to generated HTML, so modifying CSS is the only choice.
This sort of inheritance support would make life a lot easier because we'd be able to treat CSS rules as "functions" and reuse the code rather than duplicate it.
Or am I missing something and CSS does support this (I've never seen it before?) or plans on supporting it? Enlighten me please.
Edit: Consider another example which shows that declaring .awesome-image, .super-awesome-image {common rules} is not elegant:
.border5 {
border-radius:5px;
-moz-border-radius:5px;
-webkit-border-radius:5px
}
I would much rather not pile up every other class that would want to have a border radius in the same definition. Alas, that's what needs to be done without functional support (I mentioned a lot of times there's only access to the CSS file and not the HTML itself).
In CSS, this is achieved as follows:
.super-awesome-image, .awesome-image {
border: 1px #000 solid;
margin: 2px;
}
.super-awesome-image {
padding: 2px;
}
Styles can be applied to multiple classes at once, which allows for easy inheritance.
There has been much debate as to whether CSS should be given functional programming techniques or layer inheritance, but this style of class inheritance will probably remain.
EDIT:
If you can generate styles with php, such inheritance should be quite doable.
Check out these scripts (which mostly deal with CSS variables, but may do more):
http://www.shauninman.com/archive/2005/08/05/css_variables
http://www.joesapt.net/2005/09/03/08.46.34
http://interfacelab.com/variables-in-css-via-php/
http://www.conditional-css.com/
It would make recursion possible (which would mean parsers would need to be able to recover from it)
Multiple rule-sets can use the same selector, so which one would apply? Or would all of them?
You can achieve what you want with:
<img … class="awesome-image super-awesome-image">
or
.awesome-image,
.super-awesome-image {
border: 1px #000 solid;
margin: 2px;
}
.super-awesome-image {
padding: 2px;
}
It kind of does support what you're suggesting, via the Cascade and inheritance. These are essential parts of CSS to understand, but they're sometimes a bit, er, idiosyncratic ...
I think the problem you mention is valid, but in those situations where the web programmer is completely separate from the web designer, it puts the onus on the initial project management to ensure both do what they're meant to. It's obviously a good philosophy to separate function and style, but there will always have to be some kind of link between the 2 and that is carried out by specifying the external CSS file(s). That's the reason it's important to define Id's and Class's carefully and always factor in some scope for change, i.e never make your CSS too general and always define ID's and Class's in the HTML for elements even when you're not styling them right now. It's a fine line to walk though between being pedantic and being careful, but then trying to think 6months/1year/5years ahead always would be ;)
This has always been my own personal approach.
I think "mixins" in LESS or SASS do exactly that.
As for why CSS itself doesn't do that, I don't know. First, I'd like to know why CSS doesn't give me a sane way to vertical align my content, or to shrink-fit a container (with floats), or to override overflow:hidden clipping for selected elements, or to do absolute positioning in relation to opposite edges, or ... and a lot of other things.
Your idea sounds nice, though.