How strictly should I keep styling separated from the html code? - html

What is the most common or accepted way to prioritize between clean html code and clean css code?
As I see it there are two possible approaches…
Either you can go for a html code with minimal markups related to styling. The downside is that the css tend to be a bit messy and perhaps a bit redundant when you for example add similar styling to different objects (which in this approach lacks suitable classes).
The other approach results in a cleaner css code where you have predefined classes for different stylings, think w3.css or bootstrap. This time the downside is that you may end up with a html code that heavily relies on the class attribute of the tags, sometimes the combination of several classes; meaning that the html markup isn’t really separated from the styling.
I realize that there is no definite answer and that the line between the two options are floating. But what is the preferred approach, given that you are not using any precompiled framework?
Edit:
The question is not about inline css. It is about how to think regarding the use of predefined css classes. For example… if you add a class similar to “w3-panel” to some divs then you effectively add some margin in the html code. If you instead target those divs specifically by using selectors you keep the html free of styling.
The former produces cleaner css code and the latter produces cleaner html code. Which route is the most accepted one when not implementing a framework (forcing you to style by adding classes to the html)?

The advantage of the separation is to make it easier to maintain and if you find a css too messy, take a look for SASS or SCSS. And if you are using jQuery to manipulate your CSS, it is easier if you have your definitions in a CSS file. Imho the worst choice you can make is to mix it up - some definitions in CSS and other in the HTML - you may find it useful now, but try to change the site in a few months.

It really depends on your business of application.
If you put styles in same file in html file size would be increasing and it would be getting messy when you added new css each type, but as your css and html are in same file and css is well written and used, page load time would be minimum as html find css in same file.
If you put styles in separate css file, it would be well readable and accessible, you would have separate layer for styles and markup. But each your page load, your included css file would also be load in addition hence increase page load time.
If your application or html page is one time i.e no much furthur additions in future and will be remain same mostly then no need for separe css file.
If your application would be growing or html page being updating quite often, then you should be separate css files.

Personally, I think it is best from the beginning to split the code as much as possible. (HTML for markup, CSS for styling, etc).
Pro(+)
It is easier to troubleshoot
You can scale and later on introduce support tools such as SASS for CSS, etc.
A task can be splitted between persons.
Easier for another programmer to understand the setup of files.
Neg(-)
Take a bit energy to be disciplined and really keep coded splitted.
You sometimes would need a larger monitor to have the splitted codes in parallel view.

Related

Reasons to use an inline style?

What would be some good reasons to have to use inline style as oppose to an external css file or css code in the header?
One good reason to use inline styles is if you're using it for HTML emails. For every other opportunity, I think it would be best to use external styles with meaningful classes/ids and inheritance.
Not all styles can be reused; some will be used by a single element in the HTML, so having a class for that may be an overkill and even increase the overall size of the file.
Using inline style can actually make HTML more readable and maintainable when the style can't be reused for other elements (tags).
You should always try to find a way to avoid inline styles. They are often indicative of poor planning or lazy programming. That being said, they are available. Don't beat yourself up for using the tools that are available to you if a specific need arises.
The only reason I can think of is to make the HTML less readable and the CSS less maintainable. Not all styles can be reused; some will be used by a single element in the HTML, and having a class for that may seem like overkill and can slightly increase the overall size of the file - but having two different places where you have to edit the CSS makes things as a whole harder to maintain. This difficulty increases exponentially as you add more and more inline styles.
Moreover, while making changes, finding and navigating to the right HTML file to modify the inline CSS when you make a change to something else in your stylesheet can be a hassle and increases the effort of applying those changes. That's the definition of poor maintainability.

Big development teams can't handle a single CSS style sheet?

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.

Html/ css coding standards

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.

Page-specific css rules - where to put them?

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.

Minimize CSS length holding style of given HTML constant

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.