How can I transcend my confusion over CSS? - css

I am interested in improving my understanding of CSS. I have been making web pages for a while, but I am still constantly thwarted by bizarre behavior that I can't explain when I try to get things to look the way I want. I have a good bit of development experience and I have no trouble understanding the finer points of Javascript, PHP, or even C. But when it comes to CSS and HTML, I find I am always trying to "trick" my code into working.
This must betray a lack of understanding on my part about how web pages and CSS actually work. Are there any good books or resources I could look at toward the end of truly understanding what is going on under the hood? I always feel like I'm at a loss, but I suspect I could get over that if I just cracked down and did some good reading.

I find I am always trying to "trick" my code into working.
Yep. CSS is often about creating the illusion of the effect you intend, rather than actually doing what you intend.
That said, there are very specific rules, as specified by the W3C. Understanding the visual formatting model can do wonders for your understanding as well. These specs are dense, and often confusing, however, so figuring out specific properties and building knowledge step by step is often the easier way to go. Find tutorials (see links below), or just play with them and see what happens (that's how I learned float and clear).
Even though it's often dead, there are a few SO users who will check the CSS Chat Room regularly (myself included), so if you have general questions (inappropriate for an actual SO question), feel free to ask there, and someone will eventually ping you back.
Also, I've created a Useful CSS Links document with links to official documents, several tutorials, and other CSS resources.

You might be getting mesmerized by the pretty blinking lights and forgetting to watch how everything is connected together. Just like you can get too focused on how a node in the DOM is affected by your javascript, you can't forget about the parents and siblings and how they all fit together. Your biggest problems are probably positioning. Remember how all the elements are connected together and that will solve a lot of confusion.

I'm sure you've already been here, but just in case:
Learn CSS:
http://w3schools.com/css/default.asp
Learn CSS3:
http://w3schools.com/css3/default.asp
However, the best way to learn this stuff is by trial-and-error. HTML and CSS are unique in their forgiving approach to malformation/errors. This, along with the fact that no two browsers render HTML/CSS exactly alike, presents a certain ambiguity that even experienced HTML/CSS developers occasionally grapple with.
Still, learning this stuff is a blast, and really rewarding once you get a handle on it. Happy coding!

Related

A REAL quick, basic CSS layouter

Short story: I frequently have to work on many different, rather small, web pages.
Most of them are layouted with pure CSS.
My Problem:
My job is to work on the code itself, on the functionality of the pages, not on the layout. However, due to the changes I make, I am often forced to make slight layout modifications and that soaks up my time like a black hole.
I end up spending as much as 10 times as long to do the slightest layout modifications as it takes me to add or rewrite routines.
We have a designer as well but it is just impossible to wait for him to redo layouts for every change I make (and often enough I have to change things multiple times).
So what I've searched for is a super basic and simple CSS WYSIWYG editor that isn't a complicated professional design tool. After trying a few tools I gave up, going back to editing by hand. In particular, the behavior of nested layout boxes just freaks me out every time.
Does anyone have some hints on this?
I'd appreciate any help,
Thank you
Two thoughts:
1) Adopt more of an agile process
The visual design (layout) and logic design should be built in tandem rather than one after the other. As you've found out, modifying things after the fact can be a real pain.
2) Adopt a CSS framework/OOCSS methods/Component Library
The idea behind all 3 of those is to create reusable CSS that follows a predictable structure. This takes a lot more up-front work, but results in a code base that should be a lot easier to maintain going forward.
twitter bootstrap
http://twitter.github.com/bootstrap/
looks really good from first impressions.
My rails expert keeps raving about it and I'm planning on trying it. Obviously free 'n all.
Basically we've felt your pain with this issue!
Bootstrap is good for real developers, a lot of it is basic layout via css tags and I think it'll make a lot of sense to you.
Even if it doesn't meet all your needs, it might be a great place to start with, as a standard for a development team. As much as developers often dislike being templated ;)
The actual direct github site is: https://github.com/twbs/bootstrap
Is it used much? Currently?...
Github Stats:
Watcher: 8682
Forks: 1383
Last Update: 10/10/2011
This post: 10/26/2011
Looks good! :)
I'm also a big fan of HAML - Ruby + HTML without the angle brackets(and more)!
... not sure if this will help, but yahoo grid builder works well for me. Of course there is a catch. The css selectors it generates are not very semantic, so you might have to do some re-factoring of them from withing the generated html page.
Github Stats: (for Blueprint suggested by Daniel below)
Watchers: 4556
Forks: 390
Last Update: 06/06/2011
This post: 10/26/2011

Why are Grid Layouts still seeing such poor adoption?

Having recently become a convert to Grid Layouts, I find myself looking at more and more sites' code and seeing that grids are still grossly under-represented.
While I accept that grids might not always be the only right solution for every web design situation, I think that they are a tool that should be seeing higher rates of adoption than they currently enjoy.
I think if I'd known more about the design approach earlier, I would have saved a considerable amount of time and effort. But Grids don't seem to have the sort of exposure that, say, CSS standards do. Why should that be? Is it even a problem that some people might be missing out on a design approach that could potentially be a better solution to a problem they're working on?
The "Grid Layouts" you speak of, are nothing "special". What you are actually talking about, are "CSS frameworks". These "Grid Layouts" should still be using CSS Standard
You also did not mention the most popular CSS Grid Framework - YUI Grids CSS
I think the reason people normally don't use a framework, is that they don't want to be locked into something with limited customization. Also a big reason is that there is no guaranty that the framework will be around forever, and once it is gone, your knowledge with that framework is useless.
There is also some Criticism of CSS Frameworks on Wikipedia:
Lack of flexibility outside the limitations of the framework
Bloated source code
Additional HTTP requests for multiple files
Lack of substantial additional features beyond what is already available with CSS
Also I think that most web developers just like to write there own HTML/CSS.
I'm going to preface this by saying I personally have no strong feelings about grid-based layouts one way or the other. However, the reason other people may not want to dig into them is that it's a major time investment. For example, if you look over the docs and tutorials for Blueprint, it's clear that figuring out how to use it and applying it effectively for one simple project is going to cost you at least an afternoon, and that's assuming everything works exactly the way the docs say it will. If everything doesn't do that, you could be looking at several days of Googling and forum posting. Nothing against Blueprint or grid-based layouts. It's just the nature of these things.
So for all that risk and effort, here's the payoff: every element in your layout lines up on a grid.
The debate over whether that's worth the effort could go on for years. I'm not going to touch that one. Let's just say it's debatable.
I don't like them. The 960 grid sites don't work well on the iPhone/iPod Touch. And they're terrible on my Blackberry. I prefer a fluid layout that works well on smaller screens.
I don't mind if they show up as 960 on computers, but for Pete's sake, serve me something fluid on mobile. If everyone used this, I'd be happy.
I think we don't see grid layout to be so popular because to use any CSS framework you already need to know CSS on decent level, in case anything goes wrong, or because you gonna need to style your elements anyway.
So the question that asked why somebody who already decently know CSS will start using framework.
I think the best way to use framework is to rip some parts of it (like form styling) and use it with your own developed things.

How are CSS frameworks used?

For some reason, it never dawned on me that there could be frameworks for CSS. I have been working on my own personal site, and I just really hate 'designing' with CSS (I think more then a few programmers might agree with me). Anyways, I understand the benefits of a framework for a language such as Java, PHP, [insert language]. I downloaded a couple different CSS frameworks and couldnt really figure out how to use them. I guess I might be expecting an API or something (which obviously doesnt make sense given the lack of logic in CSS)...
Has anyone here used (and would reccomend) a CSS framework? Is it overkill for a relatively simple layout?
Please do not post links to other sites, I know how to use Google. I would rather hear the opinions and insights of the community. Thanks.
Please understand framework here simply as 'a collection of helpers for getting things done'. So what will you get in most cases is a set of CSS definitions, resetters and hacks, which you will probably need to code for yourself anyway when having cross-browser compatibility on mind.
No links? K. First, you should get familiar with Grid Design techniques. My fellow front-end developers recommend Blueprint for handling CSS-based layouts, no matter how complex they are. Hope this helps a little.
Caveat: I haven't really looked into this subject in a few years, the landscape may have changed.
The few CSS frameworks I've played with in the past have been more or less hideous things designed for snapping to grids, wrongheaded desires to bring WYSIWYG into the picture, and providing things like generic rounded corners and such. They tend to have some semantic issues (.italic FTL) and require a lot of manual tinkering for a framework.
More practical for the CSS beginner or rapid dev site, are perhaps the CSS reset which functions to baseline CSS across browsers (yahoo's) (Erik Meyer's). But this is not without it's own controversy and never seemed to be enough.
Basically. I find CSS requires a toolbox of common techniques of your own, but something you'll pick and choose and modify constantly. As in much of web dev I think the more experienced you get the more you find yourself wanting to roll your own.
I used YAML (Yet Another Multicolumn Layout) in a few projects, because I didn't like to "fight" with the Internet Explorer 6 HACKS.
There is a good explanation of how to use it and you can customize it to your needs (as long as you're going to use a multicolumn (2 or 3) layout).
960.gs seems to be fairly popular with designers lately, although I have never quite seen the point to CSS frameworks myself.

Is it practical to build a web site using strict XHTML and relying on CSS 100% for visual style?

I tend to take the academic approach all too often and adhere to strict principles in my development when the reality is that I could have finished the project sooner had I been a little less cautious. I'm looking to find the right amount of practicality.
I want to take the "Zen" approach to designing a site which (in my words) says "Use HTML strictly for content structure, and let the CSS magic do the rest". How practical is this in reality? One of the issues I run into is that I want to develop (make functional) the site first, then come back in and design it later. I know structure-wise how I want the site to flow, but I haven't even begun playing with the CSS layout, graphics, or any of the other designy stuff. What is the right approach here?
It's absolutely practical, and provides infinite benefit. In fact it's exactly what CSS and the separation of content and layout is designed for.
The right approach given the above, is to let different teams get on with the different tasks at hand. That requires (perhaps) an initial graphic design which can be quite rough, and a documented and collaboratively agreed set of naming conventions for things like "#viewport", ".user" etc..
The markup team will usually be backend driven and will usually lead the design team slightly, but they should and must remain flexible enough to change markup where required, or put that in the control of the designers.
This last is just my $.02, but where one person is both roles, again I think you lead yourself with the markup/backend first and then iteratively go to a design stage, then markup, then design, as required.
The approach you want to follow is the right one. Just two things:
If you use a validator for css or html, don't pretend that all your html or css pass the test. Obviously the ideal goal is that everything validates, but at a first stage I think is better not spend a lot of time in validation issues. And remember that no one validator is perfect, and the good way to use it at the beginning is to guide you in the right direction and avoid big mistakes (i.e. put the same id twice in one page, or put block elements inside inline ones...). Then, when the application is at a good stage, you can make your css and html perfect and valid.
Don't design the interface at the end. I think that the interface of the application can give you good directions in how develop your back-end too. So, at your place, I would design the interface first, with html and css, and then I'd start to add functionality to it.
(Sorry for my english, spelling corrections are welcome.)
It can be very practical and you will be suprised how clean your HTML looks. I like using a CSS reset file to help get started, I personally like the YUI reset. Another Zen item to consider is the use of unobtrusive JavaScript. This further separates the different layers of your code. JavaScript libraries, like jquery, prototype and dojo can help with this.
It can be done, and I think your site (and your web design skills, not least) will be much better for it. But it also has a certain learning curve. It requires a more thorough understanding of the XHTML/CSS specs than many people have.
Making sure your HTML can be validated is just the beginning.
Oh, and make sure all browsers run in strict mode when rendering the page.
Of course, you will require workarounds for IE support, but that can be done with several methods.
First, IE supports conditional comments, allowing you to include special CSS stylesheets just to fix IE bugs, which should get you most of the way, without affecting your compliant standard-version of the page.
For some things, you may need a bit of javascript as well, but it shouldn't be necessary for most common functionality.
There are reasons explained in http://www.webdevout.net/articles/beware-of-xhtml against using XHTML today. To summarize, XHTML is not supported unless you serve it as such and if you target older browsers (any IE version is old considering most of its features are implemented when they were still immature and not changed substantially for a while) you have no choice but serve it as HTML.
Unless you don't require features that being XML provides (like SVG, MathML), stick with HTML. You won't have any serious advantage over HTML, be any more semantic, have better CSS support (even less). But you get wider compatibility and your layout will be more predictable (for example table cells can inherit from first cell in the row in HTML, no such thing in XML, not even sure XHTML has any exceptions somewhere).
Validators won't help writing XHTML any more than HTML. Even annoy, if you use a strict one, leaving you wondering what is all the fuss about / in the br tag if you lie and say it is HTML. (Firefox view source shows it bright red if you serve XHTML as HTML). I am sure you can find more examples.
Sure, you can do that, but be prepared that it WILL NOT render under IE. On a recent web project, the majority of our front-end defects were fixing stuff in IE that already worked fine in Firefox. Maybe this will change in IE8, but I doubt it. In some cases we even had to write some javascript that would be executed on IE only to work around things that couldn't be done with just CSS.
while it sounds good in theory you cant create the layout for a site 100% with css. You still need to use some markup so that you have something to apply the css to. That said, you can come fairly close to ideal using this method. I'm constantly amazed at how little markup a true css guru actually requires.
closer the "zen" approach that you are really looking for is xslt. it works by your app generating xml data and then the xslt transforms that xml into html/css. this requires learning xslt and adds another layer of complication to the process of generating a page, but adds the separation you are looking for. In an ideal world the theory is that a programmer only has to worry about generating xml data and then a designer can generate the visuals using that data, however it rarely works that way as xslt is more technical than most designers can handle. Most of the time the programmer ends up generating the xslt which somewhat defeats the purpose.
One approach that works for me is to structure the HTML first, then add some minimal CSS in a tag in the same file (just enough to create the right layout etc). Then once you're happy with the structure, you can pull the CSS out into separate files and / or completely rework the CSS. This strikes the right balance for me - it's still a lightweight process, but it avoids the potential headache of finding and replacing inline CSS.
In theoria yes, in practice, browser differences may force you to add a bit of javascript to deal with the differences.
Now... Benefits of something is different from practicality of doing it. Are you guys forgetting IE or even the pain-in-the-whatever client who wants the impossible done?
I am tempted to say you have to make some exception to the strict DTD that you are using to make it work in a reasonable set of browsers and please your stakeholder for the website/web-app.
I am a standards freak and no one would be more happy than me if it was possible to build a website that doesn't violate even 1 DTD rule. But after 4 years, I just haven't been able to do it for practical purposes.
Sure if I am the one coming up with the requirements for the website I am going to develop, it might be possible, but I have to bend the business rules to accommodate that. Believe me, that's the only way it is possible.

Abstraction away from CSS

Many frameworks seek to abstract away from HTML (custom tags, JSFs component system) in an effort to make dealing with that particular kettle of fish easier.
Is there anything you folks have used that has a similar concept applied to CSS? Something that does a bunch of cross-browser magic for you, supports like variables (why do I have to type #3c5c8d every time I want that colour), supports calculated fields (which are 'compiled' into CSS and JS), etc.
Alternatively, am I even thinking about this correctly? Am I trying to push a very square block through a very round hole?
What I found works best is to really learn CSS. I mean really learn CSS.
It can be a confusing language to learn, but if you read enough about it and practice, eventually you'll learn the best way to do things.
The key is to do it enough that it comes natural. CSS can be very elegant if you know what you want to do before you start and you have enough experience to do it.
Granted, it is also a major PITA to do sometimes, but even cross-browser issues aren't so bad if you really practice at it and learn what works and what doesn't, and how to get around problems.
All it takes is practice and in time you can become good at it.
If by some chance you happen to be using Ruby, there's Sass. It supports hierarchical selectors (using indentation to establish hierarchies), among other things, which makes life easier to an extend from a syntactical perspective (you repeat yourself a lot less).
I am certainly with you, though. While I would consider myself a small-time CSS expert, I think it would be nice if there were tools for CSS like there are with Javascript (Prototype, JQuery, etc.). You tell the tool what you want, and it handles the browser inconsistencies behind-the-scenes. That would be ideal, methinks.
You can always use a template engine to add variables and
calculated fields to your CSS files.
This elaborates on my previous answer.
When I first started using CSS I also thought it was a pain that it didn't support variables, expressions, etc. But as I started to use it more and more, I developed a different style to overcome these issues.
For example, instead of this:
a { color: red }
.entry { color: red }
h1 { color: red }
You can do:
a, .entry, h1 { color: red }
You can keep the color declared in one spot by doing this.
Once you use CSS enough you should be able to overcome most browser inconsistencies easily. If you find that you need to use a CSS hack there is probably a better way to do it.
Sorry to say that guys, but all of you missed the point.
The word abstraction is the key. Say you and Sally are making a website. You are styling forms while she makes the corners round. Both you and she have defined a handful of selectors.
What if, unknowingly, you picked class names that clash with the ones of Sally? You see, you can't "hide" (abstract out) the details when you work in CSS. That's why you can't fix a bug in IE then create a self-contained solution that others can use as-is, much like you call procedures in a programming language only caring about pre- and postconditions and not thinking of how it works on the inside. You just think of what you want to accomplish.
This is the biggest problem with the web: it completely lacks abstraction mechanisms! Most of you will exclaim, "It's unnecessary; you stop smoking crack!"
You will instead do the job of say, fixing layout bugs or making round corners or debating on the "best" markup for this or that case over and over again. You will find a site that explains the solution, then copy-paste the answer then adapt it to your specific case without even thinking what the hell are you doing! Yes, that's what you will do.
End of the rant.
Then comes the multiple browser issue
There is this that helps remove some inconsistencies from IE. You can also use jQuery to add some selectors via javascript.
I agree with Dan, learn it and it's not so much of a problem, even fun.
See, this is the problem with SO-- every answer so far has made a valid point and should be considered the final answer. Let me try to sum up:
CSS is good! To expand further, there is a learning curve but once you learn it many things will be much easier.
(Some) Browser inconsistencies are solvable generically.
(Some of your) Variable and calculated field functionality can be taken care of through whatever templating engine you use.
I think a combination of all these certainly solves a large sum of problems (although to be fair deeply learning CSS is not an option for everyone; some people just don't use it enough to justify the time).
There are some problems none of the above points cover (certain types of calculated fields would require writing a JS library for, me thinks) but it's certainly a good start.
For variable support, I have used PHP with CSS headers to great effect for that. I think you can do it in any language. Here is a php sample:
<?
header('content-type:text/css');
header("Expires: ".gmdate("D, d M Y H:i:s", (time()+900)) . " GMT");
$someColorVar = "#cc0000";
?>
BODY {
background-color: <?= someColorVar ?>;
}
Solutions to problems seem to often involve jiggering numbers around like some chef trying to work out exactly how much nutmeg to put in his soon-to-be famous rice pudding
I only get this when trying to make stuff work in IE.
If you learn CSS to the point where you can code most things without having to look up the reference (if you're still looking up reference regularly you don't really know it and can't claim to complain I think), and then develop for firefox/safari, it's a pretty nice place to be in.
Leave the pain and suffering of IE compatibilit to the end after it works in FF/Safari, so your mind will attribute the blame to IE, where it damn well belongs, rather than CSS in general.
CSS variables are coming (relatively) soon, but I agree they are long overdue. In the meantime, it is possible to use a CSS templating engine such as Sass, or even the dynamic web language of your choice, to generate your stylesheets programmatically.
For CSS frameworks, you could consider YUI Grids. It makes basic layout a lot quicker and simpler, although used in its raw form it does compromise on semantics.
The key to a real understanding of CSS (and the browser headaches) is a solid understanding of the box model used by the CSS Standards, and the incorrect model used by some browsers. Once you have that down and start learning selectors you will get away from browser specific properties and CSS will become something you look forward to.
Also check out BlueprintCSS, a layout framework in CSS. It doesn't solve all your problems, but many, and you don't have to write the CSS yourself.
I believe the common errors beginners have with CSS are to do with specificity. If you're styling the a tag, are you sure you really want to be styling every single one in the document or a certain "class" of a tags?
I usually start out being very specific with my CSS selectors and generalize them when I see fit.
Here's a humerours article on the subject, but also informational:
Specificity Wars
CSS takes a bit of time to learn, but the thing I initially found most discouraging was the fact that so many hacks were needed to get all browsers to behave the same way. Learning a system which doesn't adhere to logic seems dumb... but I've clung to the vague belief that there is logic behind each browser's idiosyncrasy, in the form of the W3 spec. It seems that the new generation browsers are slowly coming into line - but IE6 still makes my life hell on a daily basis.
Maybe creating an abstraction layer between compliant/valid CSS code and the browsers' shoddy implementations wouldn't be a bad thing. But if such a thing was created - would it need to be powered by JS (or jQuery)? (and would that create an unreasonably burden, in terms of processing cost?)
I've found that it useful to 'level the ground' when scripting with CSS. There are probably loads of different flavours of reset script out there - but using YUI resets has helped me to reduce the number of quirks I'd otherwise encounter - and YUI grids make life a little easier sometimes.
#SCdF: I think your summary here is fair. But the argument that some people don't have the time to learn CSS is bogus - just think about for a second. Substitute a technology that you've mastered and you'll see why:
I. Hate. Java. Is there something out there that will just write it for me? Not everyone has the time to master Java.
CSS is certainly an imperfect technology - I have high hopes that 5 years from now we won't be dealing with browser incompatibilities any more (we're almost there), and that we'll have better author-side tools (I've written a Visual Studio macro for my own use that provides the the sort of variables and calculations that you describe, so it's not impossible) - but to insist that you should be able to use this technology effectively without really understanding it just isn't reasonable.
You are thinking about this correctly though, you're probably still going to need to understand the different browser implementations of CSS. This is just understanding the environment your application lives in.
To clarify: this isn't about understanding CSS. If you know the language well, you've still got to handle the redundancy, duplication and lack of control structures in the language.
Ive been writing CSS solidly for more than 10 years and I've come to the conclusion that while the language is powerful and effective, implementing CSS sucks. So I use an abstraction layer like Sass or Less or xCSS to interface to the language. These tools use a syntax similar to CSS so you're solving the problem in the problem's domain. Using something like PHP to write CSS works but is not the best approach.
By hiding the problems in the language through an abstraction layer, you can deliver a better product that will maintain its integrity throughout the full life cycle of your project. Writing CSS by hand accelerates software rot unless you're providing solid documentation which most CSS coders aren't. If you're writing a well documented CSS framework, you probably wouldn't write it by hand anyway. It's just not efficient.
Another problem with CSS is due to it's lack of support for nesting block declarations. This encourages coders to build a flat, global set of classes and handle the name collisions with a naming convention. We all know globals are evil but why do we write CSS in such a way? Wouldn't it be better to give your classes a context instead of exposing them to the whole document model? And your naming convention may work but it's just another task you must master to get the language written.
I encourage those of you who pride yourselves on writing good CSS to start applying some of the best practices from programming to your markup. Using an abtraction layer doesn't mean you lack the skill to write good CSS, it means you've limited your exposure to the weaknesses of the language.
You don’t need an abstraction away from CSS—you need to realize that CSS itself in an abstraction. CSS isn’t about putting pixels just so on the screen. Instead, it’s about writing a system of rules that help the browser make those decisions for you. This is necessary, because at the time you write CSS, you don’t know the content the browser will be applying it to; neither do you know the environment where the browser will be doing it.
Mastering this takes time. You can’t pick up up CSS in a weekend and be good to go. It’s a bit deceiving, because the language has such a low barrier of entry, but the waters run deep. Here is just a few of the topics you should seek to master to be proficient in CSS:
The Cascade and Inheritance
The Box Model
Layout methods including floats and the new flexbox
Positioning
Current best practices such as SMACSS or BEM to keep your styles modular and easy to maintain
You don't need to know this all up front, but you should continue pushing forward. Just as with other languages and programming in general, you need to continually seek to learn more and master the craft. CSS is a fundamental part of web development, and more developers need to treat it with the same respect they afford other languages.

Resources