Donkeys and Elephants and Delegates,oh my!
Check out the most popular
CSS: Getting Into Good Coding Habits
communitymx.com — In this article we will look at what might be considered best practices, or perhaps, good coding habits to get into. To begin, we will look at removing any defaults that a browser may add to our elements and then look at how we can explicitly set the values we want.
- 1564 diggs
- digg it
- bfaulk04, on 10/12/2007, -2/+11pretty general stuff, but informative nonetheless.
- Jimzip, on 10/12/2007, -1/+10It would be especially handy if you were new(ish) to CSS. I'd say I'm pretty on the ball with CSS, but still a couple of little niggly things there I didn't know that were quite helpful.
This is the sort of article that's really useful if you've been teaching yourself (which is.. a lot of people..), often it's hard to find people to ask these questions.
Jimzip :D - mutatron, on 10/12/2007, -1/+7@dugdig,
You can write code that way, but it isn't particularly good coding practice. - dasluvaluva, on 10/12/2007, -3/+5One thing I wish CSS had were "classes" or parent/child nodes.
It'd be so much easier (and collapsible in TextMate!) if you could have:
body div {
width: 50%; background: #eee;
p { text-indent: 5em; }
}
instead of:
body div { width: 50%; background: #eee; }
body div p { text-indent: 5em }
It'd be alot easier to see which styles were being inherited by parent elements, and it'd cut down on alot of the code/clutter in a CSS document.
*EDIT* Looking at it plainly, it seems more cluttered with nesting, but with syntax highlighting (ala TextMate/any-other-IDE), it could prove very useful. - palmer, on 10/12/2007, -0/+3Many of the examples given above are WRONG, folks, because you're setting either the text or background color without setting the other one. If you override the user's background or text color, you have to override them both. Otherwise, you don't know that the text and background aren't the same color.
- gguldens, on 10/12/2007, -0/+4If "dugdig" had been trained as a professional programmer, he would understand that there is a trade off between making code human readable and easily understood and "unnecessary bloat". I can do a binary compare of the month number in a date with the number 9 and tell which months have 30 days and which have 31 in just a single line of code (I can do it with 3 assember code instructions). None of that is useful unless the programmer following behind me can easily tell what I am doing in my code. That is why you write comments and write "bloated code" that is more easily understood by someone else who may not see things from the same view as you do.
- coreyb, on 10/12/2007, -0/+6@dugdig
Try maintaining a site that is written like that, even if YOU wrote it say 6 months ago, when you are on a short deadline and don't have time to "sift" through the garbage to find what you just broke...
It is then that you will realize that it is just good coding practice. - ElMoselYEE, on 10/12/2007, -0/+5dugdig: readability is much more important than saving 20 bytes of memory, especially with memory becoming so cheap nowadays. now, you may say that it taxes the server unnecessarily. while this is true, who -- exactly -- has SO much traffic, that 20 bytes of bandwidth will save their web server? probably not yours (or any of ours, for that matter), and even so -- if that was the case -- you'd be much better off optimizing somewhere else that made a bigger impact, such as SQL queries, or optimizing server-side CPU usage.
- resplence, on 10/12/2007, -0/+3@dugdig:
If you can REALLY read that, especially after working on it for several hours, then more power to you. But if we ever work together, please conform to what's considered readable by the majority of non-mutant human beings. Otherwise I will be forced to show your code to our non tech-savvy boss so he can see for himself why it is impossible to work with you :)
- Jimzip, on 10/12/2007, -1/+10It would be especially handy if you were new(ish) to CSS. I'd say I'm pretty on the ball with CSS, but still a couple of little niggly things there I didn't know that were quite helpful.
- FrankieB078, on 10/12/2007, -9/+1already down!
- noahhoward, on 10/12/2007, -1/+39Couldn't his line:
html, body, ul, ol, li, p, h1, h2, h3, h4, h5, h6, form, fieldset, a {
margin: 0;
padding: 0;
border: 0;
}
simply be written as:
* {
margin: 0;
padding: 0;
border: none;
}
That's the way I've done it for years and it seems to do the same thing.- Jimzip, on 10/12/2007, -0/+4Write to him and he may edit the article. I'm sure he probably knows it, but I have a feeling this is for people that aren't used to more advanced CSS.. anyway it's worth a try!
Jimzip :D - isthisnametaken, on 10/12/2007, -1/+4thanks for the tip, I didnt know that!
- brendanc, on 10/12/2007, -1/+11Yes, you can do that, however that applies 0 margin/padding to ALL elements, not just the ones he defined. He defined all common elements, but not form elements. Just FYI, as using * may have an undesired effect for some people.
- daharris, on 10/12/2007, -8/+1surely
html {
margin: 0;
padding: 0;
border: 0;
}
would do the trick too? - tizz66, on 10/12/2007, -0/+3noahhoward: You're both right, in a way. In the article, he included the border in the css definition. Applied to *, though, that will remove the border on everything that you (probably) want to retain a border (buttons and text boxes, for example). So if you do it the usual * {} way, just leave out the border: 0; line to avoid that problem, or do it his way and leave it in, up to you.
- noahhoward, on 10/12/2007, -0/+1Those are all good points. Maybe I'll see if he could elaborate in the article and explain the resoning behind including certain fields... of course, that may be outside th escope of his article.
- noahhoward, on 10/12/2007, -0/+2Doesn't seem to be any way to contact him.
- cedric, on 10/12/2007, -0/+1You're not wrong with sugesting the use of a wildcard but I hear it's pretty heavy on the browser rendering engine.
- ignorantcow, on 10/12/2007, -2/+1* loops through ALL possible elements, performance degrades.
daharris: No- but html * { property: value; } would; but that's essentially the same as what * { rule: property: value; } is targeting, minus html.
- Jimzip, on 10/12/2007, -0/+4Write to him and he may edit the article. I'm sure he probably knows it, but I have a feeling this is for people that aren't used to more advanced CSS.. anyway it's worth a try!
- ReiToei, on 10/12/2007, -16/+1I stopped reading the article when it mentioned inline styles
- bpapa, on 10/12/2007, -2/+19You should have kept reading, as he explains why not to use them.
- quux, on 10/12/2007, -3/+2@ReiToei
"A foolish consistency is the hobgoblin of little minds..."
Don't ask me to explain foolish versus wise consistency. I'm not that smart. - nofxjunkee, on 10/12/2007, -2/+3What, when it mentioned that they were the exception and not the norm? Oh, you jumped the gun and stopped reading before that bit eh?
- ElMoselYEE, on 10/12/2007, -0/+2so did you read all the previous comments thinking, "all of these people are stupid, only idiots use inline styling"?
- FauxOne, on 10/12/2007, -6/+1I disagree that *.lightblue is a bad selector. If you have a color that you use in only certain instances in your content, on different elements, it is useful to have a class that only applies that color or style. For example:
[style]
.lightblue { #9CF; }
.bold { font-weight: bold; }
[/style]
[p]
I [span class="lightblue"]really[/span] enjoy the flavor of Newcastle.
[/p]
I think another good habit for CSS is applying multiple classes to a single element, like so:
[p]
Augue qui nulla sit ex [span class="bold lightblue"]veniam erat[/span] suscipit exerci vero consequat dolore eu, ea, [span class="lightblue"]consequat at[/span].
[/p]- chadu, on 10/12/2007, -3/+11what if the client changes their mind and says that they want the "lightblue' text to become green?
- jhaven, on 10/12/2007, -2/+5Why would you declare a bold class on a span?
Just use the strong element. It's what it was designed for...
[strong class='lightblue']lorem ipsum[/strong] - grammarpolice, on 10/12/2007, -6/+3@ chadu: then just change the blue hex color to a green one in the Css file. Also you could *find & replace the text with dreamweaver, I have changed my mind several times and all I do is find and replace text, it takes 2 seconds.
Cheers. - jhaven, on 10/12/2007, -0/+7@grammarpolice: "then just change the blue hex color to a green one in the Css file"
But the class is called 'lightblue'. If you change the color declaration to green, then the class name loses its meaning and obfuscates the markup..
A better option than naming the class 'lightblue' would be to name it something like 'alt_color', since it is, in fact, an "alternate color". It's a meaningful name, and you can freely change the color declaration without sacrificing semantics. - synotic, on 10/12/2007, -1/+4Using CSS to hardcode presentation in the code completely goes against the whole point of CSS.
Doing:
[span class="blue"]Hello[/span]
Is no different from:
[font color="blue"]Hello[/font]
CSS exists to separate the presentation from the content. It forces you to rethink your content and design:
-Why- are you making the text blue? Does it emphasize the text? Why not use the [em] tag? But you already use the [em] tag to make other text italicized? Then why is some emphasized text light blue while other text isn't? Is it because you want all of the emphasized text in your sidebar to be light blue, as the design of the sidebar is different? Then use #sidebar em.
Again, CSS causes you to rethink your content and design. Defining .bold classes and .lightblue classes is pointless. - palmer, on 10/12/2007, -0/+3And, if you're making the text blue, are you making the background something that isn't blue? If you pick a text color, you have to set the background to something different. An undefined background color is not automatically white; it's whatever the prevailing window-background color is on the user's system. Same goes for text: It's not automatically black, so if you hard-code your background to white, you have to make sure the text isn't white.
On any OS except the Mac, the user can set up any color scheme he likes. Your site looks pretty inept when it's mostly blank. - CircleFusion, on 10/12/2007, -0/+1The point is...
Why do you have to make changes in two places (or worse...50 html files and your CSS file) with a search/replace when you only want to change the color of a class?
If you made the class name alt_color or something similar, then you would only need to make one change in the CSS file and NOT TOUCH your HTML code.
This is very important for very large projects.
Where I work (a company in the top 10 of the fortune 1000 list) we have some big projects. The HTML team often does the frontend layout and passes that off to the server-side developers for them to implement in a web application. If we had to change HTML when someone wants to change a highlight color, then it would take a week to get it done, that is, if we had to do a search and replace to change the actual HTML from saying class="lightblue" to class="lightteal".
If we named the classes appropriately (like alt_color), then we wouldn't need to change the HTML at all, and would only need to change the CSS file. The change takes effect within an hour. - gguldens, on 10/12/2007, -0/+1Absolutely excellent points on both sides of this issue! I believe there is a place for both format specific declarations and generic declarations. I don't believe this issue is as cut and dry as some of the comments seem to want it to be. This thread has really started me thinking about my CSS declarations and my naming of them. From where I sit, this thread has prompted me to make myself a better coder. Now, isn't that the whole point of the original post?
- tizz66, on 10/12/2007, -0/+4A good CSS coding habit is to indent declarations that are related... e.g.
.some_class {
...
}
[tab] .some_class a {
[tab] ...
[tab] }
I find that helps to keep things organised and helps you locate classes more quickly, especially if you're CSS is quite large.- CircleFusion, on 10/12/2007, -0/+1I personally love indents (as long as the text editor defines a tab as 4 or less characters and not 8 characters).
But I know that some people don't like indenting code for whatever reason. I personally don't understand that stance. I've seen people who prefer to put all of their CSS attributes on one line. I've looked over their shoulder while they were coding. When they have to make changes to a CSS attribute, it takes them a few extra seconds to find the attribute in the long mashed-up format. Sometimes, they would overlook an attribute altogether. It may save some screen real-estate, but it sucks to sort through, especially when the project gets really big.
I tried using extra CSS indenting to help organize similar selectors (like you suggested), but I heard moans from one of my coworkers about it so I stopped doing it. :-/
- CircleFusion, on 10/12/2007, -0/+1I personally love indents (as long as the text editor defines a tab as 4 or less characters and not 8 characters).
- cpoteet, on 10/12/2007, -0/+1Informative, but what's sad is that this information still needs to be heard and headed by a large majority of developers. If I see one more tag I quit.
- inkswamp, on 10/12/2007, -1/+5I think these kinds of tutorials are great for beginners (and even clarifying various things for seasoned pros) but I shudder a little bit when I read definitive statements like this: "An external CSS file is the way to go." Well, no, not really. If you've ever done this kind of work professionally, you'll find that there are many times (for far too many reasons to get into here) when inline and embedded are just fine and do what they need to do. Planting this absolute idea in the minds of newcomers that there is an Absolute Right and Absolute Wrong way to do it is detrimental, I think. You develop a sense of where to use what. There is no right and wrong about this stuff.
- itsaghost, on 10/12/2007, -1/+19"CSS: Getting Into Good Coding Habits"
Funny how the website doesn't even validate.- grammarpolice, on 10/12/2007, -1/+7You made my day.
- grammarpolice, on 10/12/2007, -1/+7You made my day.
- Patranus, on 10/12/2007, -9/+4USELESS - I call shenanigans on ALL of these articles about XML and CSS validation.
Look, here is the deal. Anyone in the real world of web programming will tell you that you use what works NOT what the "standard" tells you to use. W3 is NOT a standard when it does not work correctly in the market leader - IE Internet Explorer(IE?). Because IE does not render pages to the wW3 standard means that W3 is NOT a standard at all.
Look at all of the fortune 500 web sites. The vast majority use tables. Tables have been taboo in the web dev community for years yet these companies pay millions of dollars for web sites that use them. Why?
Because they work. You know how it is going to work in EVERY browser out there. You gain stability and compatibility by using them ever though they are not good practice.
Why is it bad to use a CSS hack when it works?
Why is it bad to not have your site validate w3 when it works?
IT IS NOT BAD.
I am kinda sick of all these people who say that they are doing it the "right way" when in fact there is no right way.
I will admit that resources like this might be good for beginners but in the long run you will throw all of that out.- shockingbird, on 10/12/2007, -2/+3I totally agree with you.
You could write 100% valid code that semantically perfect and have multiple browsers render it differently.
Until all browsers are valid themselves, talking about how important standard code is isn't really that great. - tizz66, on 10/12/2007, -0/+6Did you read the article? It isn't about writing standards-compliant code, it's about writing good quality code that does what you expect it to.
- wfbnadador, on 10/12/2007, -1/+7you both are completely wrong. this comes down to the core separation of content versus presentation.
http://www.youtube.com/watch?v=6gmP4nk0EOE&eurl= watch that. i wont waste my breath.
progress takes work, and no. internet explorer is not the standard. if it were, they wouldn't have released ie 7 with css updates
and you can target browsers with css, so if you're up to snuff and take the time, it will render properly in all browsers - jaythree9, on 10/12/2007, -2/+1In one sense i agree, because in the end you need to have a working website that's not going to look drastically different in every browser. But what you are also talking about is the reality today. Standards are about going towards the future. As the people who actually create the stuff rendered on crappy browsers (im pointing at you, IE), we need to not roll over and just accept whatever tripe they toss at us. We are allowed to have a say, and that say is standards.
- synotic, on 10/12/2007, -0/+5The problem with perceptions like these is that they are incredibly myopic. What works for -you- doesn't necessarily work for everyone else. I would mention people with disabilities who use other means of viewing online content, but since we're talking practically, I suppose we can ignore the "crippled." They don't make much money for companies anyway.
Or I could mention how technology these days is moving towards the internet. Using physical media for movies and music is passé. Using the internet (the full, interactive internet, not the watered down kind) on your phone or on your TV or on your media device is becoming reality. Going forward, tables don't work.
I could also mention how the government won't do business with you if you use tables for layout. If we're talking about money, there's large chunk right there. Look into Section 508.
Table based websites are stagnant. There's a reason they're so prevalent, especially in the business sector. They don't have the resources to change them. Websites that people -actually- use, on a regular basis are CSS/HTML based. Sites like Digg, Facebook, and Google's network of sites are the ones that are surging and making unbelievable amounts of money. CSS and Ajax have enabled Web 2.0. Google Maps anyone? If anything, the best way to make money these days is to embrace open standards, not ignore them.
- shockingbird, on 10/12/2007, -2/+3I totally agree with you.
- themoose, on 10/12/2007, -2/+1I already do most of this stuff, so dugg so other people can find it.
- bagelpirate, on 10/12/2007, -4/+1www.duggmirror.com
- bagelpirate, on 10/12/2007, -1/+3http://www.duggmirror.com even
- bootle, on 10/12/2007, -1/+2CSS is more formatting than coding. Not a big deal, just a teeny misnomer, imo.
- thailand1972, on 10/12/2007, -0/+0@synotic - you make TABLE sound like it's a deprecated tag. You are one of these CSS extremists living in a binary world of RIGHT and WRONG. Tables are good for....wait for it.....tabular information. Wow. The TABLE tag is good at tabular information. CSS is clumsy for this kind of thing when tables work fine. Of course tables can be abused for trying to do layout and you see some websites with tables nested 4 or 5 deep. But even in those bad examples, the HTML is used validly even if it's an inelegant way to layout a page. I'll say it again: the HTML is still used perfectly validly. The TABLE tag isn't going away because it doesn't need to. Your 'fundamentalist' opinion just makes me think you read too many CSS blogs. Take a step back and you'll see there's a holistic approach to web development. How many beautiful CSS sites don't even have a different color for visited links? Answer : the vast majority. Talk about bad usability. But...but...but....my beautiful menu looks bad with two colors of links....sorry this is the web - usability and accessibility are king - not how beautiful your CSS is.
- thailand1972, on 10/12/2007, -0/+0@synotic again:-
"Sites like Digg, Facebook, and Google's network of sites are the ones that are surging and making unbelievable amounts of money. CSS and Ajax have enabled Web 2.0. Google Maps anyone? If anything, the best way to make money these days is to embrace open standards, not ignore them."
Ajax is not a standard. It's a mash-up of javascript and server-side coding. It's a hack of sorts and is actually not new - it's just been given a name recently. It makes websites function very well to those who have javascript enabled and hopefully these sites degrade well to those who don't use javascript - but some don't work at all without javascript. A site that doesn't work unless you have javascript enabled is standards compliant? Whose standards exactly??
Also I don't understand your point about making money and using Ajax. Google's search is old fashioned HTML using tables. I hear they're making some money. I think a good idea + good execution is more important than whether you use Web 2.0 or not.- synotic, on 10/12/2007, -0/+0thailand:
Tables are fine for tabular data. The two phrases I used were "tables for layout" and "Table based websites."
I also never said anything about validating a website. A site that I'm working on uses Safari's "invalid" type="search" box, which turns it into a search field. Other browsers ignore it and just render it as a text field. This is fine by me. My personal belief is that it's good practice for your HTML to be well formed (it makes it easier, for instance for a site to parse the data if you don't have an RSS feed available), however, having validated HTML is really only -important- to me where the difference between valid and invalid code affects the website. The HTML can be well formed when using tables (from a syntactical standpoint), but that isn't what's being debated.
For some layouts, tables are a remarkably efficient way of organizing data, from a presentation standpoint. CSS still struggles with certain layouts (full height columns, for instance). The problem here, is that it's only effective in presentation. Let's say you've created a basic site with 10 pages. Want to change the sidebar from horizontal to vertical? You have to change every single page. Sticking to semantic tags like H1, H2, H3, and P forces you to think in a top down approach, while leaving the left to right, up and down presentation to one file that you can easily change.
You're right that CSS can be abused. The lack of a distinct color for visited link is a good point. For this particular argument, however, it's only a side note.
If usability and accessibility is king, then I wouldn't be looking towards tables for layout. I also didn't comment about "beautiful" CSS. I personally like to keep my CSS consistent, and indented, but only to show me structure of my website. It makes it easier for me, but people have their own personal habits.
You make a good point about Ajax. I got a bit carried away, comparing the older web with the new. It is still a messy technique. I had also said "open standard," in that it's not restricted to any browser, like Active X.
My argument about money + Web 2.0 was towards the comment that companies pay millions for table-based websites. Of course it's good ideas and execution that mark success for a website, but certainly "the money isn't all in table-based sites." That was my point.
I'm not exactly sure why you're attacking me, as I don't really disagree with much of anything you're saying, and what I'm saying doesn't really go against what you're saying (as I said earlier, I said nothing of throwing out tables or validating web pages).
Sorry if there was any confusion.
- synotic, on 10/12/2007, -0/+0thailand:
- thailand1972, on 10/12/2007, -0/+0@synotic,
Thanks for the reply - hope you're still reading this thread - coming in a bit late here to reply back to you.
Well it seems we're actually pretty much in agreement then. Certainly I agree 100% that semantically laid out (X)HTML is vital - particularly for search engines. Want to know the main heading of a page? Don't wrap it in meaningless FONT tags. Give it its due - the H1. Web pages should easily be understood by people, browsers and search engines. This is where semantics come into play.
Don't worry synotic, you were a proxy to my own distaste to 'web extremists' - those who talk in absolute terms. The TABLE tag is useful, and has always been useful. It certainly has and is being abused. This doesn't make it not useful though (as you have said yourself in reply). I totally agree with you that good development means avoiding the 'search and replace' clumsy method of update and instead have a stylesheet that controls all web pages. This is the same for programming where you use functions, procedures, include files etc. It makes sense to change once, and affect many pages.
Anyway, thanks for getting back and explaining yourself :)
Browsing Digg on your phone just got easier with our enhancements to the