Which of these CSS rules renders faster? - css

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.

Related

div#name vs #name

I know that in a stylesheet div#name and #name do the same thing. Personally I've taken to using div#name for most styling I do, with the reasoning that it's slightly faster, and means that I can identify HTML elements more easily by looking at the CSS.
However all of the big websites I seem to look at use #name over div#name (stack overflow included)
In fact I'm finding it very difficult to find many websites at all that use div#name over #name
Is there some advantage to doing #name that I'm missing? Are there any reasons to use it over div#name that I don't yet know about?
Since the div part of div#name is not required (because ID are unique per page), it makes for smaller CSS files to remove it. Smaller CSS files means faster HTTP requests and page load times.
And as NickC pointed out, lack of div allows one to change the HTML tag of the element without breaking the style rule.
Since ID's have to be unique on the page, most ID's you'd run into would only ever appear once in your style sheet, so it makes sense not to bother including what element it would appear on. Excluding it also saves a few characters in your style sheet, which for large sites which get visited millions and millions of times a day, saves quite a bit of bandwidth.
There is an advantage to including the element name in the case where a division with ID "name" might appear differently than a span with ID "name" (where it would show a division on one type of page and a span on another type of page). This is pretty rare though, and I've never personally run across a site that has done this. Usually they just use different ID's for them.
It's true that including the element name is faster, but the speed difference between including it and excluding it on an ID selector is very, very small. Much smaller than the bandwidth that the site is saving by excluding it.
a matter of code maintainability and readability.
when declaring element#foo the code-style becomes rigid - if one desires to change the document's structure, or replace element types, one would have to change the stylesheets as well.
if declaring #foo we'll better conform to the 'separation of concerns' and 'KISS' principals.
another important issue is the CSS files get minified by a couple of characters, that may build up to many of characters on large stylesheets.
Since an id like #name should be unique to the page, there is no reason per se to put the element with it. However, div#name will have a higher precedence, which may (or may not) be desired. See this fiddle where the following #name does not override the css of div#name.
I would guess that including the element name in your id selector would actually be slower – browsers typically hash elements with id attributes for quicker element look up. Adding in the element name would add an extra step that could potentially slow it down.
One reason you might want to use element name with id is if you need to create a stronger selector. For example you have a base stylesheet with:
#titlebar {
background-color: #fafafa;
}
But, on a few pages, you include another stylesheet with some styles that are unique to those pages. If you wanted to override the style in the base stylesheet, you could beef up your selector:
div#titlebar {
background-color: #ffff00;
}
This selector is more specific (has a higher specificity), so it will overwrite the base style.
Another reason you would want to use element name with id would be if different pages use a different element for the same id. Eg, using a span instead of a link when there is no appropriate link:
a#productId {
color: #0000ff;
}
span#productId {
color: #cccccc;
}
Using #name only:
Well the first obvious advantage would be that a person editing the HTML (template or whatever) wouldn't break CSS without knowing it by changing an element.
With all of the new HTML5 elements, element names have become a lot more interchangeable for the purpose of semantics alone (for example, changing a <div> to be a more semantic <header> or <section>).
Using div#name:
You said "with the reasoning that it's slightly faster". Without some hard facts from the rendering engine developers themselves, I would hesitate to even make this assumption.
First of all, the engine is likely to store a hash table of elements by ID. That would mean that creating a more specific identifier is not likely to have any speed increase.
Second, and more importantly, such implementation details are going to vary browser to browser and could change at any time, so even if you had hard data, you probably shouldn't let it factor into your development.
I use the div#name because the code is more readable in the CSS file.
I also structure my CSS like this:
ul
{
margin: 0;
padding: 0;
}
ul.Home
{
padding: 10px 0;
}
ul#Nav
{
padding: 0 10px;
}
So I'm starting generic and then becoming more specific later on.
It just makes sense to me.
Linking div name: http://jsfiddle.net/wWUU7/1/
CSS:
<style>
div[name=DIVNAME]{
color:green;
cursor:default;
font-weight:bold;
}
div[name=DIVNAME]:hover{
color:blue;
cursor:default;
font-weight:bold;
}
</style>
HTML:
<div name="DIVNAME">Hover This!</div>
List of Css selectors:
http://www.w3schools.com/cssref/css_selectors.asp

Is it bad to overwrite styles in CSS?

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...

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?
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.

How do you organise CSS in your project? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
One of the most challenging thing I have felt while working on (complex) web application is the organizing the CSS.Here are the different approaches we have tried on multiple projects.
1: Have a different stylesheet for every web page/module.
Obviously we were very new to web apps then, and this approach resulted in too many style sheets and too much repetition of styles. We had a tough time to achieve consistency across the application.
2: Have a common style sheets which is shared across the similar web pages.
This worked well for sometime until it became too complex. Also we found that we had too many exceptions which still resulted in tweaking common styles for particular cases, which if done incorrectly can affect different parts of the application and at some point it becomes difficult. Also having a large development team (across different time zones) and tough project timeline didn't helped our cause.
Although #2 works, but still we have seen our products still doesn't have the similar UI quality and consistency as we would like to.
Are there any CSS style guidelines that one should refer for very complex web 2.0 application. How do other people maintain their stylesheets?
I've found myself in similar situations.
First off, make sure that you're using CSS effectively. If you don't feel like you're an absolute pro at using CSS, take some time to study up and you'll significantly reduce redundancy and end up with a stylesheet that's easier to work with.
In most cases, there isn't much of a performance hit if you consolidate all of your styles into one file, and in fact, splitting your styles into dozens of files just so that you can be sure to exclude any that won't be used is likely to result in longer loading times because of all of the extra requests. But as I'm sure you know, a massive CSS file can quickly grow into a headache to maintain.
Consider this hack to achieve a compromise. Use your language of choice (PHP for me) to serve up your CSS. By that I mean include your style file like this:
<link rel="stylesheet" type="text/css" href="styles.php" />
, have the header of that file return it with the text/CSS content type, and have that file
a) Pull multiple stylesheets into one file
and/or
b) Change how the styles are written depending on various parameters (file being loaded, user data, time of day, etc.)
A is a good solution overall for reducing developmental headache and page-loading overhead. B will likely necessitate you also setting appropriate file expiration dates to avoid having the browser just ignore whatever new styles you want to generate at the moment in favor of what was downloaded on the last visit. Since you can usually accomplish the same thing in B as you can by simply having a static stylesheet and dynamically-written element class/ID names, it's generally not an ideal solution unless if you're doing something really strange.
And get a designer to advise you on this kind of stuff. Often it's hard for us developers to wrap our heads around some of the finer points of efficient CSS as well as people trained in that specific area.
I've been in this a lot of times. First, in the early times, I used to do just a stylesheet with everything inside, not much anyway, was the old times; then I decided for your second approach, the first one I luckily thought it was a mistake, too much code and pieces floating around...
The second approach is good up to the time when you start to make questions...
I mean:
Should the background style for this div go in the graphic.css or in the layout.css?
Should the font style go in fonts.css or in layout when comes to the width of the P?
Should the margin for a title with the icon position div go to the graphic.css or to the layout.css or to the fonts.css (it would be simpler to use the same declaration for the icon, the text and the position...)?
Then you realized there's something wrong about this approach.
What I do now is commenting. A LOT.
template.css -
/* ////// Headers ////// */
#header {
width: 1004px;
height: 243px; /* 263H-20MARG=243H */
padding: 20px 0px 0px 0px;
background-color: #000000;
background-image:url('../images/redset/top1-bk.png');
background-repeat:no-repeat;
background-position:right top;
clear: both;
}
/* logo */
#logo {
background-image:url('../images/redset/wh-logo.png');
background-repeat:no-repeat;
width:327px;
height: 263px;
float: left;
margin: -20px 0px 0px 0px;
}
#logo a {
width:327px;
height:263px;
}
/* Top menu & Banner */
#menuybanner {
text-align: center;
/* margin-right: 65px; optional*/
}
#bannerz {
height: 152px;
width: 653px;
text-align: left;
margin-right: 24px;
/* optional: width: 100%;
margin: 0px */
}
#bigmenu {
text-align: left;
margin: 18px 0px 14px 74px;
}
#bigmenu img {
margin: 0px 22px 0px 0px;
}
Originally this would have been in three different css: layout, graphics and texts. Now I know what everyone does.
By the way I know it rises the weight of the archive but I prefer not to do some mixed effects, cause everyone that comes after me and reads the css should be able to understand what I did and css like these:
a, .b, .c, .d, #f, #2 { background-color: black; }
Are really hard to unveil. Of course if you need to do it, go ahead, but I mean, sometimes they are just grouped like for nothing just to be more cryptic... like moodle... hahaha.
Hope being of help.
See ya.
You want to take advantage of cascading nature of CSS and the ways rules are inherited.
Code first the most general cases and then change specifics.
For a normal size project this should not get out of hand at all.
To see things more clearly you can use an index sheet and call other stylesheets from it. When you want to make changes you will know which stylesheet to go to and you will save time. Here is an example from one of my prqjects.
/*
This is the CSS index page. It contains no CSS code but calls the other sheets
*/
#import url("main/reset.css");
#import url("main/colors.css");
#import url("main/structure.css");
#import url("main/html-tags.css");
#import url("main/sign-up-sign-in.css");
#import url("main/pagination.css");
#import url("main/menu-items.css");
#import url("main/teachers-list.css");
#import url("main/footer.css");
#import url("main/misc-custom-sections.css");
#import url("main/error-messages.css");
Good luck finding your own style.
I use one mastersheet template.css which styles my main template. For any site which requires a seperate bit of styling that can't be covered by the main template I either put it in the site head, if it's short, or create a new sheet for that case.
Ideally I want to design the template.css file to be flexible to cover most cases.
I typically try to group my CSS by visual elements, and only include relevant stylesheets for a given page to keep my load times low. Using PHP or whatever environment you use to dynamically merge the required stylesheets into a single stylesheet for a given page is a good solution.
One thing that helps me is that I actually created pseudo namespaces for my CSS. I know that CSS 3 has support for namespaces, and that makes it easier, but since some browsers don't support it, this is what I do:
Create folders and files relevant to your project ( I use Java namespace style )
For example /css/com/mydomain/myprojectname/globalheader.css
Next, I use class names that map to the file system location
For example <div id='header' class='com-mydomain-myprojectname-globalheader-topClass'>
Use separators and good comments in your css file
For example /*---------------------------- begin link section --------------------*/
Use PHP or whatever to load these files and combine them into one stylesheet on load ( you could cache the resulting sheets if you are really clever. The namespace convention will prevent collisions between class names.
While the designers think this is verbose, it makes it really easy to find specific css classes in the file system, without a load time hit. Also, you won't have the problem of one designer / developer overwriting another's classes.
maintaining css files is a LOT easier if you can get everyone on board with utilizing cascading properly and keep your targeting strengths to the minimum.
Make sure that elements inherit styles and that overrides aren't too heavy will keep your css from getting crazy. By doing this, you then allow yourself to have just 2 or 3 style sheets for layout/base styles and overrides. If you put heavy control levels on what gets into the layout/base style sheets, and make regular trips in to reassess whats in the overrides sheet to see what can be moved up to the base and what can be simplified you'll free yourselves up to allow people to override at will, but also to keep control of creep.
There's my theory...

CSS Performance

Usually when I build a site, I put all the CSS into one file, and all the properties that relate to a set of elements are defined at once. Like this:
#myElement {
color: #fff;
background-color: #000;
padding: 10px;
border: 1px solid #ccc;
font-size: 14pt;
}
.myClass {
font-size: 12pt;
padding: 5px;
color: #ee3;
}
I've been considering splitting up my definitions into a number of different files (colours.css, layout.css, fonts.css ...) as I have seen recommended. Something like this:
/* colours.css */
#myElement {
color: #fff;
background-color: #000;
border-color: #ccc;
}
.myClass {
color: #ee3;
}
/* layout.css */
#myElement {
padding: 10px;
border: 1px solid;
}
.myClass {
padding: 5px;
}
/* fonts.css */
#myElement {
font-size: 14pt;
}
.myClass {
font-size: 12pt;
}
To reduce HTTP requests, I'd be combining the files and stripping whitespace prior to rollout, so that's not an issue, but my question is: does having all those selectors repeated over and over cause any performance issues in browsers?
Alternatively, are there any tools which avoid this (potential) issue by merging definitions from different files? ie: take the input given in my second example (3 different files), and combine them into one file, like the first example.
The browser will have to find all the definitions and then add them up and override the different properties based on the latest definition. So there will be a slight overhead.
That being said it would be rather minimal and not very noticeable even on hardware 5 years old. The browsers are quite efficient at it these days.
I can't comment on performance, but I tried this approach on my website and ended up reverting to one large file.
My reasons:
I got tired of creating a rule for div.foo in three or four different files, and opening three or four files if I wanted to change that div.
Sometimes it's not as easy as it should be to separate functions. To center a div in IE, you may have to center the text of the parent element, even though that's not the standard way. Now my layout is mixed in with my fonts.
As the code grows, the easiest way for me to find things is to do a text search for the element I want. But I have to open several files to see all the rules, and maybe that element doesn't have a rule in this file so I get no matches.
So I went back to having main.css and iehacks.css. And breathed a sigh of relief.
As William said, you're not going to see any issue from the browsers parsing the CSS. What you might see, though, is an issue with the number of HTTP requests that a client can open to a single host. Typically this defaults to two. So, if you do put your CSS in multiple files, you might want to put them on a separate sub-domain and they will be treated as a different host which will allow the HTML page to be loaded at the same time as your CSS files.
There shouldn't be any noticeable difference in rendering/parsing speed. As everyone else said, computers are fast enough that they can render CSS pretty quick.
Your problem is really going to be with the number of requests required to load the page. Extra web requests increase overhead when loading a page. It is much faster to load one large file than it is to load several smaller files. It has an impact on both the client (browser) and the server serving up all of those CSS files.
As long as you combine your files in production, you should be fine.
Yahoo's YUI Compressor is a pretty good tool for compressing your CSS files into smaller files. The last time I checked, it can't definitions (at least the last time I looked at it) but there shouldn't be enough of a performance hit to really need to.

Resources