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.
Related
I use the 2 ways but I prefer the first due to reuse code. some prefer one or other. But I would like to know if the load in big stylized pages is better in one way than the other.
1)
<style>
.red{ color:red}
.right25{ margin-right: 25px}
.bold{ font-weight:bold}
</style>
<p class="red right25 bold">this is a red text, bold and right margin 25px</p>
2)
<style>
.class1{ color:red; margin-right: 25px; font-weight:bold}
</style>
<p class="class1">this is a red text, bold and right margin 25px</p>
That depends on how much of the code that you can actually reuse, but the performance difference won't be that big.
The biggest difference between the approaches is what the classes mean. Generally you should have classes that represent what you are trying to show, not exactly what styles you use to show it. Names that represent the intent rather than the implementation fares better when you make changes.
For example if you have the class right25 and want to change the margins to 20 pixels instead, then you either will have a class name that doesn't represent what it actually does, or you have to change it to right20 everywhere that you use it.
Two is your answer. The browser reads each class from right to left. Reading one class is faster than reading two classes.
http://csswizardry.com/2011/09/writing-efficient-css-selectors/
http://css-tricks.com/efficiently-rendering-css/
Use the external stlye sheet. The browser can cache that.
http://www.w3schools.com/css/css_howto.asp
You're absolutely talking about the first method that could be slower than the second method?
To answer: There's no difference in speed of styling css.
To illustrate:
div{
color: blue;
padding: 10px;
}
div{
color: red;
font-size: 16px;
padding-left: 5px;
}
When css is applied over the rule, the following css will be applied by the browser:
div{
color: red;/*later one*/
font-size: 16px;
padding: 10px 10px 10px 5px;/*padding-left 5px is taken from later rule*/
}
And which is parsed by the browser at the same time when the div gets styled from the stylesheet.
Why there's no difference?
In any other programming language like JavaScript if one line gets error then another line doesn't run and so from that line of code the interpreter won't go to read the whole code.
But in css language there's no problem even if you write rules whether html has no such classes or id, there's no problem reading next line of code even if you have some mistakes in your stylesheet, whatsoever the browser will load entire stylesheet file and read the code and gives the output in same time (when stylesheet is fully loaded) and both of your code doesn't seem to be any difference in the speed.
By the way, it could be slower (that even you can't catch with your eyes) where there is slower internet connection below 32kbps because of stylesheet downloaded the line by line of code.
Which CSS authoring technique do rendering engines process more efficiently:
1) repeating the same style property/value pair in multiple selectors, or
2) grouping shared style properties in a single selector
Example 1: Duplicate font-size, but less rules
p {
font-size: 1em;
color: #000;
}
h1 {
font-size: 1em;
color: #fff;
}
or Example 2: More rules but one font-size
p, h1 {
font-size: 1em;
}
p {
color: #000;
}
h1 {
color: #fff;
}
This study by Dave Gregory is the best source I've found on this topic. It shows that duplicating property/value pairs is much worse for performance:
"Long" is what Gregory refers to as the "bloated" format where properties are repeated in multiple selectors.
for performance is better the second option, see this google advice, but take care of using declarations in just one place, you could finish with something like this, this is the problem with extend in css preprocessor like sass and stylus. However your first option could be more modular and makes your css modules more independent and reusable in other sites, you can then make use of a css minifier to group every declaration.
Organizing your css is really up to you and the number of elements you have.
If you are looking for optimization you should instead focus on useless whitespaces and duplicates.
Tools exist to merge the duplicates and minimize your code (here and here for example)
You may also read this article which is a bit old but still valuable I think.
I hope this question isn't too weird and arbitrary. When I'm viewing some CSS using Firebug, I've noticed that the CSS properties for each tag are in alphabetical order.
Is it trying to tell us something?
Apart from the obvious benefit of being able to find the property you're after more quickly, I was wondering this: Is it quicker for a browser to apply the properties if they are in alphabetical order in the original stylesheet?
For example is this...
body {
background: #222;
color: #DDD;
font-size: 0.85em;
}
#content {
background: #444;
padding: 1em;
}
p {
border-bottom: 0.9em;
line-height: 1.2em;
text-align: justify;
}
...better than this...?
body {
font-size: 0.85em;
background: #222;
color: #DDD;
}
#content {
padding: 1em;
background: #444;
}
p {
text-align: justify;
line-height: 1.2em;
border-bottom: 0.9em;
}
Can this be tested effectively?
This would obviously be replicated throughout the entire stylesheet so would a browser benefit from doing things in order and, if so, would it be worth revisiting past stylesheets to reorder things?
-- edit --
Ok, a slight alteration to my question: What if the attributes are always in the same order for each tag. Background always before border always before color etc and so on (I know I've missed some!) for each and every tag. Alphabetical would aid you in keeping things in order rather than being the optimal method.
Looks like the overwhelming consensus is that it matters not, however!
There's definitely no speed benefit in ordering your styles alphabetically.
If you want real speed benefits, you should minify your CSS.
There are so many programs to do that, but here's one of them: CSSTidy. This program also has the option to put your styles in alphabetical order (if you want that for your benefit).
I don't think order of statements affects speed in any way, however, the efficiency of the statements can affect performance. (Slightly tangential, I guess...)
See: http://code.google.com/speed/page-speed/docs/rendering.html#UseEfficientCSSSelectors
The performance benefit is for visual parsing only - FireBug will re-arrange your style attributes into alphabetical order when you inspect an element, which I find much quicker to locate a style attribute.
Firebug do it so that developers can search for an attribute value easily, and if you want speed benefit, write your css judiciously, which includes mainly avoiding repetition and redundancy and being DRY
Also when a page loads and CSS is parsed and layout is rendered once, next time its not done again, so stay calm, and try to make it more maintainable instead
Writing CSS in an alphabetical order just makes one thing easy: finding your attribute. It has nothing to do with speed.
To Increase speed, you can use shorthands rather than using separate attributes. Things like border-color, border-width, border-style can be used in a single attribute called border.
Does separating CSS code into multiple declarations cause more overhead for users?
I have seen some .css files organized like so:
/* Font Styles */
#text{ font-size: 12px; color: white;}
.highlight{ color: red}
/* END */
/* Div Positioning */
#text{ position: absolute;}
/* END */
Could this cause any potential inefficiencies? I understand that something on this scale will have no noticeable effects, but what about on massive style sheets?
Common sense says that the more rules you have, the more overhead there will be. However, CSS parsing is usually quite fast, so I wouldn't worry about it unless your stylesheets are truly ginormous.
It can, but only if you have thousands of selectors. Read this article for more info:
http://www.stevesouders.com/blog/2009/03/10/performance-impact-of-css-selectors/
I think theoretically the answer has to be yes.
The browser must parse the new rule, it must look up the #text element again in the DOM and it must perform any new layout/rendering calculations.
Though as you point out, wait until this is a problem before you start optimizing.
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...