I'm building my first website for an internship. My instructors always told me to never embed any styles on my html page.Now that I'm actually creating a site I find it annoying that, if I want to change the color of my font for a span tag - I have to I.D. it and reference it in a css file. Is there some other reason then organizational purposes for using CSS? Would embedding a single style be such a convention breaker? Thanks for reading this and I'd appreciate any feedback.
There are a couple of reasons.
Times when you want to change the style of a single element on a single page should be exceedingly rare, so it shouldn't be such a hardship. Any other time, it is going to be more efficient (from an HTTP caching perspective) and easier to maintain (from a separation of style and structure perspective) to externalize the style information.
Since there is a good chance that you'll want to style it differently for different media (e.g. screen and print), you'll need a proper stylesheet for that too.
If you embedd a style to several HTML pages, and want to change it later, you have to go file by file changing it. That is one good enough reason for me.
The key word here is maintainability. Organized code is maintainable code! It is far better to add an id to a tag and reference it in the global css file than to do it inline, because if you want to change that style later, you know where to find it, and you only have to change it in one place.
The reason you want to offload the CSS into a different file is so the browser can cache it. Otherwise, the browser has to load all the CSS as well as all the markup on every page. If you keep it in a separate file, the browser only has to load the CSS once.
The basic argument for this is that HTML's purpose is to provide structure while CSS's job is to provide styling, by embedding CSS in HTML you're breaking this basic rule. Plus, you'll have a tough time in maintaining pages.
Ideally, a design should be consistent enough that you can use generic rules for such situations. If you want to emphasize something, then <em> or <strong> is likely the way to go. After styling your <em> or <strong>, you can easily add the same emphasis to other areas of the site.
It's not simply about performance or style, it's also about consistency and ease of maintenance.
Find the similar elements in your design and mark them up similarly. It's as easy as that.
Even if it's "just 1" you should still do it because it helps you get in the habit of it.
embedded css has the following problems:-
1. It has browser compatibility problem. Example Ie has problem understanding inbuilt styling.
2. If you want to use the same css style again , it is better to have a class for it.
Related
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Inline styles vs styles in CSS
i guess i'm looking for some opinions on this. I am all for using css styles as classes in a separate .css file. But every once in a while, i run into a scenario where i need just some padding for a particular element or change the css class' width only in one particular situation. Is it okay to add inline styles in those scenarios? do people do this or always create classes for everything.
My theory would be if its not something reusable or does not contain more than 2 styles, why create a class for it. Am I wrong in thinking that?
Summary of Answers (since there are many)
It is better to avoid inline styles because
1) style sheets provides more maintainability.
2) better separation of html data and layout.
3) re-usability of styles.
4) probably provides better caching.
Overall, css style sheet is the best practice.
Anything is reusable if you think it through and set it up correctly. Even one-line, one element CSS attributes can be beneficial if reused. This takes advantage of the concept of caching, which will keep the css in memory after the initial load hit. No matter which way you slice it, inline styles add to your overhead every load without question.
Never mind the fact that inline mixed with a proper css document adds overhead to your own debug time, figuring out where the darned calls are coming from.
Two answers to this one:
1) It's considered good practice to keep your design (css) and your data (html) separate. By adding in-line styles, it makes it more difficult to revise the look of a site, it makes it more difficult for future programmers to modify your site, and is overall NOT the best way to go.
If everything is in a CSS file(s), then you can change the entire design of your site without having to mess with the data (HTML) of the site. This is ideal.
2) Yes, a lot of people still use inline styles very often when tweaking something small, regardless of "best practice".
You said: "if its not something reusable or does not contain more than 2 styles"
I would add another reason to use external stylesheets: maintainability. If you (or someone else) has to fix your code in the future, you will have a much easier time of it if all of your styling is in one place. You will not remember that you added that little bit of styling inline, and you may spend hours hunting for it.
It is a good standard to keep all styling separate to maintain clean, maintainable code.
That said, we can acknowledge that it is "ok" to use inline styles, as you asked in your question. However, best practice is often something more than "ok" and should serve as a guide as often as possible.
I feel like a good balance is all that you need. While its typically considered better practice to create classes as much as possible, there comes a point when its just easier to use an inline style. Like you said, if there's just that one element that needs that minimal extra padding, its not a crime to give it that. At least, in my opinion it isn't. But definitely be in the habit of making classes for just about everything, except minor exceptions.
Its not just about re-use, its about getting into the habit of doing things correctly. What if someone else needed to help you on the project, they would have to sift through your whole file to find every instance of an inline style somewhere...
People who know their CSS always create a specific style rule for everything.
Thats my opinion and I believe it to be shared among my colleagues.
A big point for me is: maintenance. When all of the CSS is in external stylesheets, it is going to be relatively straightforward to find the styles your looking for to edit them. If there are inline styles, it will be harder to find what you're looking for.
I'm usually skeptical about claims that a style never be reused. If it happened once, it is likely to happen again. Coding for reusability is always a good idea and usually results in cleaner, better written code in my experience.
Even in these situations, I will usually add a unique class somewhere up in the target element's ancestors - often on the body tag - that I can use to target the the "unique situation" and keep all the CSS in the external stylesheet.
That being said, I do occasionally use inline styles. When I do, it is almost exclusively in a situation where I know that I will be animating styles with JavaScript after the page has loaded. I only do inline styles for the properties that I am going to animate and the rest go in the external stylesheet.
I am currently in a 5-7 large development team creating a really large website with lots of pages and features.
I feel like we are in such a situation where a developer can change the style sheet to suit his own needs, but is unaware of the 1000 places where it probably change it for something else. I cannot blame him either, since I know it's hard to check everything.
It's a total mess.
I know that using one single style sheet file saves bandwidth and prevents duplicated code and maintenance, but I cant help wondering - is using style sheets a good idea for big sites, or should it be more object/element oriented.
Let's say you forget about the crazy large CSS and you define the CSS on each element instead. So each time you render a GreenBuyButton, it has the "style='bla bla bla'" on it. And this is pretty much done for all elements.
This will increase the bandwidth, but it will not create duplicated code.
Could this be a good idea or how does really large teams work on a single website do with CSS to avoid it being a mess?
Why don't you create multiple CSS sheets depending on the area of the site?
blog.css
accounts.css
shopping.css
Then you could have a serverside script (say PHP) combine all CSS into 1 sheet which will get you the same result of 1 small file (could use a minimizer as well).
Check your overall site with a CSS checker to find duplicates (css defined) and manage it that way.
Otherwise communication is key between your team, who develops what, and so people don't duplicate CSS definitions. A master CSS keeper would be best suited to manage the CSS styles, besides your team should have an agreed upon style and not go rouge creating their own unique styles.
My recommendation would be to use the CSS rules on specifity to help you. For each CSS that is not global, put an activate selector on, for example
.user-list .p {
font-size: 11pt
}
.login-screen .p {
font-size: 12pt
}
This will make it easy to identify what rules are for which pages, and which rules are global. That way developers can stick to their own set of styles, and no mess up anyone else's.
Change how you write CSS.
Instead fo treating every area of the website like a specific piece of markup that needs styling, start defining broad classes.
Enforce some rules. Like, "All <ul> have a specific look for this project." If there are multiple ways you want to style an element, start using classes. This will keep your website looking uniform throughout. Uniformity reduces broken layout.
Create building block classes like a "framework" of sorts. This has helped me so often that I never start a project without doing this first. Take a look at the jquery-ui themeroller framework to give you the idea. Here's an example:
.icon { display:block;width:16px;height:16px;}
.icon-green { background:url(/green.png);}
.icon-blue { background:url(/blue.png);}
Then on the elements:
<span class="icon icon-green"></span>
<span class="icon icon-blue"></span>
Breaking your styles up into their building blocks like this and using multiple classes on the element will keep your team members from having to change styles to suit their needs. If a particular styling quirk is not available they can define a new set of classes.
UPDATE:
Here is an example of how I used this method: Movingcost.com. Huge website, multiple different sections and pages, and only 252 lines of uncompressed css. Actually, these days I break things down further than I did on the movingcost project. I probably would have gone through those elements at the bottom of the stylesheet and figured out how to combine some of those into classes.
Multiple CSS files and combine in code
While doing development I found out that doing it the following way seems to be reasonable and well suited to development teams:
Don't put any styling into HTML. Maintainability as well as lots of head scratching why certain things don't display as expected will be really bad.
Have one (or few of them) global CSS that defines styles for global parts. Usually defines everything in template/master. Can be bound to master page or to generic controls used on majority of pages.
Have per-page/per-control CSS files when they are actually needed. Most of the pages won't need them, but developers can write them
Have these files well structured in folders
use naming and formatting guidelines so everyone will be able to write/read code
Write server side code taht will combine multiple CSS files into a single one to save bandwith.
You can as well automate some other tasks like auto adding per-page CSS files if they're named the same as pages themselves.
Doing it this way will make it easier to develop, since single CSS files will be easier to handle due to less content and you will have less code merging conflicts, because users will be working on separate functionality most of the time.
But there's not feasible way of automating CSS unit tests that would make sure that changing an existing CSS setting won't break other parts of your site.
My favorite override trick is to assign the id attribute on the <body> of each page. It's an easy way to make page specific changes without breaking out a separate stylesheet file.
You could have the following html
<body id="home">
<h1>Home</h1>
</body>
<body id="about">
<h1>About</h1>
</body>
And use the following css overrides
h1 {color: black}
#about h1 {color: green}
The home page gets the default css while the about gets overridden.
Using style sheets on large sites is an excellent idea. However, it only really works when you apply your team standards to the style. It makes sense to have a singular template controller that links your style sheet(s). It also makes sense to appoint someone on the team as "keeper of the style" who all changes to the style sheet should go through before making substantive changes.
Once the style standards are agreed upon and defined, then all of the controls in the site should implement the styles defined. This allows developers to get out of the business of coding to style and simply coding to the standard. Inputs are inputs, paragraphs are paragraphs, and floating divs are a headache.
The key is standardization within the team and compliance by all of the developers. I currently lead a team site that has upwards of 30 style sheets to control everything for layout, fonts, data display, popups, menu and custom controls. We do not have any of these issues because the developers very rarely need to edit the style sheet directly because the standards are clearly designed and published.
The answer is in the name. The reason it's called cascading style sheets is because multiple can be combined and there are decent rules defined on which one takes preference.
First of all, doing all your styling inline is a ridiculous idea. Not only will it waste bandwidth like nothing else, it will also result in inconsistency. Think about it for a while: why would changing a line of css 'break' another page? That indicates your css selectors are poorly chosen.
Here are my suggestions:
use one css file for the basic site look. This css file is written by people doing mainly design, and as a result the site has a consistent look. It defines the basic colors, layout and such.
use another css file per 'section'. For instance, a 'shopping' section will use components that are nowhere else on the site. Use that to define section-specific stuff
put page-specific styling directly in the page (in the header). If this section becomes too big, you're doing something wrong
put exceptional styling directly on the components. If you're doing the same thing three times, abstract it out and use a class instead.
choose your classes wisely and use the semantics for naming. 'selectedSalesItem' is good 'greenBold' is bad
if a developer changes a stylerule and it breaks the rest of the site, why did he need to change it? Either it's an exceptional thing for what he's working on (and should be inlined) or it was basically broken on the rest of the site as well, and should be fixed anyway.
If your css files become too big to handle, you can split them up and merge them server-side, if you want.
You don't want to define CSS for each element because if you ever need to make a change that affects many elements one day, say the looks of all the buttons or headers, you will be doing a lot of Search/Replace. And how to check if you forgot to update one rule to keep your site consistent?
Stephen touched on a very strong point in CSS. You can assign multiple classes to an element.
You should define some basic rules that "ordinary" developers can't touch. They will provide the consistency through the site.
Then developers can assign an extra class to personalize any property. I wouldn't assign more than two classes though: a global and a personalized.
Considering you already have this huge stylesheet in your hands, I'm not sure how you will pick which one of the 7 developers will have to sit down through a month and organize it. That is probably going to be hard part.
First off, you need to extract your website's default element styling and page structure into a separate stylesheet. That way people understand changing those rules affects the entire site's appearance/structure, not just the page they're working on.
Once you do that, all you really need to do is document / comment all of your code. A person is a lot less likely to write duplicate code in a well-documented stylesheet, and that is a fact.
As someone who is beginning to make a transition from table based design to full CSS I'm wondering if using the style attribute to make adjustments to elements is considered "cheating" and if absolutely ALL presentation should be strictly in the style sheet?
See also:
A question of style - approaches to styling and stylesheets
There are cases where you know for sure that all you want to do is tweak the style of this one specific element, and nothing else.
In those cases you can happily use an inline style attribute. But then, at some point in the future, you'll realise that in fact you need to apply the same style to something else, and you'll realise you were wrong.
Been there, done that. 8-)
I feel there's an aspect that has not been touched upon here: the distinction between hand-edited HTML snippets and generated HTML snippets.
For human editing, it's probably better and easier to maintain to have the styles in a file.
However
As soon as you start generating HTML elements, with server-side scripts or with some kind of JavaScript, be sure to make all styles required for basic functionality inline!
For example, you wrote some kind of JavaScript library that generates tooltips. Now, you will inject DIVs into your page, that will need some styles. For example, position: absolute and, initially, display:none. You may be tempted to give these elements the class .popup and require that this class has the correct definitions in some CSS file. After all, styles should be specified in the CSS file, right?
You will make your JavaScript library very annoying to reuse, because you can no longer simply copy and invoke one .js file and be done with it. Instead, you will have to copy the .js file, but also have to make sure that all styles required by the script are defined in your CSS file, and you have to go hunting for those, and make sure their names don't conflict with classes you already have.
For maximum ease of use, just go ahead and set the required styles directly on the element as you create it. For styles that are purely for aesthetical purposes, such as background-color, font-size and such, you can still attach a class, to give the consumer of your script an easy way to change the appearance of your script elements, but don't require it!
You can use the style attribute, but the point of using CSS is that you make a change in a single file, and it affects the entire site. Try to avoid it as much as possible (old habits die hard)
It's not maintainable. All of us have done it. What you're best to do is put every adjustment into a style. Let me teach you something most developers do not know about CSS ... you can use N styles at a time.
For example, imagine you have a great style for colorized divs called someDIVStyle:
.someDIVStlye
{
background-color: yellow;
...
}
You want to use it, but just want to adjust the background-color to blue. Many people would copy/paste it and then make a new style with the change. However, simple create a style like this:
.blueBackground
{
background-color: blue;
}
Apply it as such:
<div class="someDIVStyle blueBackground">...
The style furthest to the right always overrides the properties of the styles preceding it. You can use a number of styles at once to meet your needs.
I agree with some other posters that it is best to keep the style information in the stylesheet. CSS tends to get complicated quickly, and it is nice to have that information in one place (rather than having to jump back and forth from HTML to stylesheet to see what styles are being used).
A little off-topic tip: Pressing F12 in IE8 brings up a great tool that lets you inspect the styles of elements in web pages you're browsing. In Firefox, FireBug does the same thing. Those kinds of tools are lifesavers if you want to know how a style change will affect an element.
It's a very "personal" question, to me the word "ALL" is a very strong word. You should do your best to have most of the styling in your css. but you can use style occetionally if it makes your life easier.
Generally it is best to have styles on the style sheet especially if it will be used multiple times, but using the style attribute is definitely not "cheating". A quick look through the stackoverflow source shows many examples of this.
Yes, it's kind of cheating, but it's up to you if you want to cheat a little. :)
The fundamental idea of having the styles in a style sheet is to separate the content from the layout. If you use the style attribute you are still mixing layout within the content.
However It's not that terrible, as you can quite easily move the style into a class. It's quite handy during development to be able to set a style on a specific element so easily without having to make up a class name and worry how the style will cascade.
I sometimes let the style attribute go through in the production code, if it's something that is specific for just one page, and if it's doubtful that it will be there for long. Occationally just because I am pressed for time, and it can be cleaned up later on...
So, even if you use a style attribute sometimes, you should still have the ambition that all the styles should be in a style sheet. In the long run it makes the code easier to maintain.
As others have said, in general, no.
However, there are cases where it makes perfect sense. For example, today I had to load an random background image into a div, from a directory with an unknown # of files. Basically, the client can drop files into that folder and they'll show up in the random background image rotation.
To me, this was a clear reason to dynamically build up the style tag on the div.
In addition, if you're using, for example, the .net framework with webforms and built-in controls then you'll see inline styles used anyway!
There can be very good reasons to put style information in a specific page.
For example, if you want to have a different header background on every page (travel agencies...), it is far easier to put that style information in that specific element (better, in the head of the document...) than to give that element a different class on every page and define all those classes in an external style-sheet.
The style attribute does have one important use: setting style programmatically. While the DOM includes methods to manipulate style sheets, support for them is still spotty and they're a bit heavyweight for many tasks, such as hiding and showing elements.
Yes, the style attribute is frowned upon in general. Since you're moving to the CSS method from table-based, I'd strongly recommend that you avoid inline styles. As a previous poster pointed out: bad habits are hard to break and getting into the habit of using inline styles for their temporary convenience is a mistake. You might as well go back to using the font tag. There's really no difference.
Having said that, there are occasions where it makes sense to use a simple inline style, but first develop the habit of using stylesheets. Only when you're comfortable with putting everything in a stylesheet should you start looking at shortcuts.
I think that's the general consensus of everyone who posted an answer
Often when I'm designing a site, I have a need for a specific style to apply to a specific element on a page and I'm absolutely certain it will only ever apply to that element on that page (such as an absolutely positioned button or something). I don't want to resort to inline styles, as I tend to agree with the philosophy that styles be kept separate from markup, so I find myself debating internally where to put the style definition.
I hate to define a specific class or ID in my base css file for a one-time use scenario, and I dread the idea of making page-specific .css files. For the current site I'm working on, I'm considering just putting the style definition at the top of the page in the head element. What would you do?
Look to see if there's a combination of classes which would give you the result that you want. You might also want to consider breaking up the CSS for that one element into a few classes that could be re-used on other elements. This would help minimize the CSS required for your site as a whole.
I would try to avoid page-specific CSS at the top the HTML files since that leaves your CSS fragmented in the event that you want to change the appearance of the site.
For CSS which is really, truely, never to be used on anything else, I would still resort to putting a #id rule in the site-wide CSS.
Since the CSS is linked in from a different file it allows the browsers to cache that file, which reduces your server bandwidth (very) slightly for future loads.
There are four basic cases:
style= attribute. This is the least maintainable but easiest to code. I personally consider use of style= to be a bug.
<style> element at the top of the page. This is slightly better than style= because it keeps the markup clean, however it wastes bandwidth and makes it harder to make sweeping CSS changes, because you can't look at the stylesheet(s) and know what rules exist.
page-specifc css: This lets you have the clean HTML and clean main CSS file. However, it means your client must download lots of little CSS files, which increases bandwidth and page loading latency. It is, however, very easy to maintain.
one big site-wide CSS: The main advantage of one big file is that it's only one thing to download. This is much more efficient in terms of bandwidth and latency.
If you have any server-side programming going on, you might be able to just dynamically combine multiple sheets from #3 to get the effect of #4.
I would recommend one big file, whether you actually maintain it as one file or generate the file through a build process or dynamically on the server. You can specify your selectors using page-specific IDs (always include one, just in case).
As for the answer that was accepted when I wrote this, I disagree with finding a "combination of classes that gives you the result you want". This sounds to me like the classes are identifying a visual style instead of a logical concept. Your classes should be something like "titlebox" and not "red". Then if you need to change the text colour on the user info page, you can say
#userInfoPage .titlebox h1 { color : red; }
Don't start applying classes all over the place because a class currently has a certain appearance that you want. You should put high-level concepts into your page, represented by HTML with classes, and then style those concepts, not the other way around.
I would set an id for a page like
<body id="specific-page"> or <html id="specific-page">
and make use of css override mechanism in the sitewide css file.
I think you should definitely expand the thought process to include some doubt for "page specific css". This should be a very very rare thing to have. I'd say go for the global style sheets anyway, but refactor your css / html in a way that pages don't have to have super-specific styling. And if in the end there's a few lines of page-specific markup in the global css, who cares. It's better to have it in a consistent place anyway.
Defining the style in the consuming page or inlineing your style are two sides of the same coin - in both cases you are using page bandwidth to get the style in there. I don't think one is necessarily better than the other.
I would advocate making an #Selector for it in your site-wide main stylesheet. The pollution is minimal and if you really have that many truly unique cases, you may want to rethink they way you mark-up your sites.
I would put them in a <style /> tag at the top of the page.
It's not worth it to load a page-specific CSS file for one or two specific rules. I would place it in tags in the head of the document. What I usually do is have my site-wide CSS file and then using comments, section it up based on the pages and apply specific rules there.
As you know style-sheet files are static files and cached at client. Also they can be compressed by web server. So putting them in an external file is my choice.
For that situation, I think putting the page-specific style information in the header is probably the best solution. Polluting your site-wide style sheet seems wrong, and I agree with your take on inline styles.
In that case I typically place it at the top of the page. I have a page definition framework in PHP that I use which carries local variables for each page, one of which is page-specific CSS styles.
Put it in the place you would look if you wanted to know where the style was defined.
For me, that's exactly the same place as I would place styles that were used 2 times, 5 times, or 170 times - I see no reason to exclude styles from the main stylesheet(s) based on number of uses.
Suppose A.css styles B.html. What tools/techniques are there to programmatically reduce the size of A.css while holding its styling effects on B.html constant? Here are some techniques I would imagine such a tool using:
Remove redundancies in A.css. For example, if the same class is defined twice you can remove the second definition without affecting semantics. This seems pretty easy.
Remove style definitions that aren't used. Does A.css style any elements that don't appear in B.html? If so, remove them.
Combine styles where appropriate. If A.css defines styles for div.x and div.y and every div that happens to have class x also has class y, one could combine the class definitions in A.css.
A different strategy would be to have a tool that examines the computed styles of each element in a piece of styled HTML and spits out the minimal style sheet that would preserve the computed styles. Does something like this exist?
UPDATE
Let me explain how I got in this situation. The CSS file in question is for an email, and it was created by basically copying a similar CSS file that we used in an associated web page. Because the HTML in the email is a proper subset of the HTML in the web page from which the CSS came, some of the CSS in the email is superfluous.
Generally you just remove all unnecessary whitespace. Remember to keep the original as well, so you don't lose readability when editing the site later.
I think making sure css files are gzipped by the webserver is your biggest bandwidth saver.
"Does something like this exist?"
Of course. See the CSS Tidy tool.
I do not believe that it removes unused css, though. See Sitepoint's Dust Me Selectors for that.
Unless you have an usually large CSS file, I would opt for readability and modifiability of the CSS file rather than having a smaller CSS file. Since CSS files are static (for the most part), most browsers will do a really good job of caching them. While all your suggestions are good ones, combining things that are the same now for different document elements can wreak havoc in the future when you only want to change one of those items.
I'm not aware of tools to remove redundant styles, but if you want to reduce file size for performance reasons there are several minifing tools out there:
See:
The art of Scaling
A better CSS minifier
A good idea is to compress your css.
This isn't zip-style compressing, it's actually re-writing the CSS (aka minification).
Of course, you can use mod_gzip or mod_deflate as well.
OK, you don't want a small file for the KB (using gzip compression is more effective!) but to prune the obsolete styles, which indeed would improve maintenance.
I don't know if the ideal tool you want exists, but Firebug (an extension for Firefox) can tell you want are the CSS elements used by a given HTML element. Not automated, but still a precious tool.
You can also edit the live CSS, to see if removing a style element alters the HTML page.