#wrapper { smart-level= 0% }
October 1, 2012 9:12 PM   Subscribe

Please help me overcome this weird language hump I have with CSS.

Design student, currently enrolled in interactive design class. Part of that class is learning some basic CSS. For some reason I'm having issues with it. I'd just teach myself [like I do with most things] but I can't even really explain where the issue is. I don't even know what I don't know. With html, I understood it on such a fundamental level that I could figure things out on my own. I could read an html document and translate it like a language. I just *got* it. With CSS, I can sort of read through it and figure out through deductive reasoning what it's doing. But as soon as I go to write some on my own, my brain goes "hrrrrrrrrr". This is a very weird feeling for me that's never happened before. My partner says I have a degree in Fucking With Shit. I can usually look at something and just figure out how it works and replicate it. But not with css. I just don't get the language.

So, the basics. I need them. I need it explained to me like I'm 7. Like, in English: an adjective goes before a noun, and the verb usually goes after the noun. But for CSS.
posted by FirstMateKate to Computers & Internet (26 answers total) 32 users marked this as a favorite
 
Have you tried tinkering with things in Firebug? There's a mode where you can sort of hypothetically edit the CSS for a page you're viewing and see what it would look like if you changed the values, deleted lines of CSS, etc.
posted by Orinda at 9:15 PM on October 1, 2012 [2 favorites]


I'm just learning some CSS myself. I found the two videos on CSS from this Google series: Google: HTML, CSS, and Javascript from the Ground Up to be really helpful. I watched them each about 3 times before things started sticking.
posted by pilibeen at 9:22 PM on October 1, 2012 [1 favorite]


Hmm. Since you're not sure where the disconnect is, it's kind of tough to figure out how to help you.

HTML describes the structure of a document, and CSS describes the presentation of that structure.

So, for instance, H1 is the HTML tag for a top level heading. Say you wanted all headings to be bold and black. To style this using CSS, you would do something like this:

h1 {
color: #000;
font-weight: bold;
}

The basic structure, then, is this:

selector {
property: value;
}

That's CSS at its most basic level. Learning the modifiable properties and values and writing complex selectors is something you pretty much have to learn by doing and studying other people's stylesheets. You need to learn the difference between margins and padding, whether you need to reset a browser's default styling so that you can "start fresh" with your stylesheet, and how to write clean, semantic HTML to make stylesheets useful. Then of course there are the browser bugs to work around.
posted by xyzzy at 9:26 PM on October 1, 2012 [1 favorite]


Well you know how in HTML where you'd made a table and it had maybe sixteen different cells in it? And if you wanted to change the way the text looked in those cells, you'd have to edit all the different cells? And if you wanted to change it again later you'd have to edit them all again and it was awful? CSS would give you one single place where you can say "Every time there is a TD element, apply this formatting to it" and then if you wanted to change the formatting you could change it once, in the stylesheet and not mess with the HTML. Or you could have two different "classes" of TD element, one called "light" and one called "dark" and tweak the colors for all the light ones and/or all the dark ones by adjusting the stylesheet.

There are also two main things CSS does: formatting and layout. Formatting is "Make this text look a certain way/color/size" and Layout is "Put this stuff in a certain place on the page." Formatting is more or less simple. Layout is harder because a lot of things are sort of defined relative to other things.

The "Aha!" moment for me in really understanding the power of the stylesheet was messing around with CSS Zen Garden which is one page that you can view with a number of different style sheets that you can then take apart and peek at. Between that and glish's CSS layouts page, I had enough examples to tinker with that I could put it together sort of like I did with HTML.
posted by jessamyn at 9:33 PM on October 1, 2012 [6 favorites]


Every CSS declaration is like this:

Selector { rules }

That's it. The selector tells you what tag the rules apply to.
Apple {
  color: green;
}
This is a rule for an apple. I'm telling that apple to be green.

You can also select via ID or classname.
apple.granny-smith {
  color: green;
}
apple#in-my-lunchbox {
  color: green;
}
The first is an apple that's classified as a granny smith. I have IDed the second apple as being in my lunchbox. There are many other apples, but this one, and only this one is mine. ('Cause you can only have one of any ID in a page)
apple#in-my-lunchbox worm {
  eaten:half;
}
There is a worm in my apple. I have declared it to be half eaten. In the same way, you can target things like
ul.fancy li {
  bla:bla;
}
which will target li's in all ul's with the classname fancy.

Now you know selectors!
posted by fnerg at 9:36 PM on October 1, 2012 [5 favorites]


If i were to liken the structure of CSS to parts of speech or even writing in general, I'd make the following analogy. All parts of a CSS document are like a list of directions that define a document (HTML or otherwise) in terms of its parts and what those parts look like and do so that a browser can make an accurate picture of what the site is. It's kind of like giving a verbal account for a police sketch I suppose. The classes within CSS are, to a certain extent, adjectives (when "defining" what a document looks like), verbs (in that CSS can define what a document does, though not in the way Java can), and adverbs (in that classes can define the degree to which an element can do something on the page or pages to which the CSS style is applied). You can get really picky with the sentences you write, being as brief or as verbose as need merits, and like a good essay, falling somewhere in between the areas of extreme minimalism and total flowery nonsense is sort of the goal.

I don't know if that helps, but I know what you mean about HTML and I think CSS will suddenly take on the same fluidity in your mind very soon. You're just looking for the right codex.
posted by These Birds of a Feather at 9:42 PM on October 1, 2012 [1 favorite]


HTML creates elements of the page. Those elements have names you get to make up (id=""), and they can be classified as belonging to categories you get to make up (class=""). They can also have a long list of qualities (style=""). Those qualities are called CSS properties, and you don't get to make them up, but you do get to set their values (property: value;). You basically have to memorize what the possible properties are and what their values can be, just like you memorized what the possible HTML tags were.

CSS properties can be put into separate files, where you have to say what tags, ids, or classes they pertain to before listing the style properties. The part where you say what tags, ids, or classes the CSS properties pertain to is called the selector. Then, inside curly braces, you list the properties you're applying to the tags, ids, or classes mentioned in your selector.

There are some special rules for dealing with special conditions, like whether the HTML is intended for a web page, a printout, or a handheld device, where you might want to style its elements differently, but that's a topic for another day.

Here's a short course that pretty much covers it all--very well.
posted by Monsieur Caution at 9:45 PM on October 1, 2012 [1 favorite]


Inline vs. block:

Since the web started as a way to publish documents, everything sort of falls into the metaphor of words on a printed page. The web, from the very beginning, was thought of more like terminal output than the crazy-assed interactive experiences we have today, therefore stuff just kinda got printed across the page until it hit the end, and then it wrapped, or else it was a block of text, which meant that you got an automatic line break, and a new paragraph. This is the heart of inline vs. block.

Inline just means things keep going on the same line until they hit the edge of the page, and then it wraps. Block means it's a box that sits on whatever side of the page that the justification requires. Block also means that you can give the element dimensions, margins and padding. Inline gets nothing, because it's just a word.

Then of course, we get to play with floats...

Ever seen an illuminated manuscript with the big-honking beginning letter things that everything else flows around? That's a float. Specifically,
float: left;
Float tosses the element to the left or right, and makes EVERYTHING flow around it. Block, inline, everything. Wanna turn a ul into a bunch of nav items across the top of a page? Float left the fuck out of them. TA-DA instant nav.

Now you know the basics layout and page flow!
posted by fnerg at 9:48 PM on October 1, 2012 [1 favorite]


What everyone else said, except - what happens if you have two selectors that contradict one another? like:

h1 {
color:red;
}

and:

.green {
color: green;
}

And you have HTML that looks like this:
<h1 class="green">...

What color is the text in this h1 tag, red or green?

It depends on "selector specificity" which is defined in this fun formula. In this case, your text ends up green, because classes are more specific than tag types. What happens if you have two rules that apply and have equal specificity, like you add this to the above:

.blue {
color: blue;
}

<h1 class="green blue">...

Now what?

It turns out the *last* rule wins, where last means, "the one your browser read latest" meaning in a CSS file linked lower down in your HTML file, or if both rules were in the same CSS file, the one closer to the bottom.
posted by tylerkaraszewski at 9:53 PM on October 1, 2012 [1 favorite]


Actually, if you look at Mefi's nav, it's a ul declared as block, floated right, and given a text-align of right. All the li's are inline, which makes them march across the page like a sentence. THis another way of making a nice nav.
posted by fnerg at 9:55 PM on October 1, 2012


Lastly, margins and padding.
  This is the margin
+---------------------+
| This is the padding |
|                     |
|    Content here!    |
|                     |
|     More padding    |
+---------------------+
      More margin
The hitch is that the actual width of you element will be margin-left+padding-left+width+padding-right+margin-right, and not just your width declaration.

box-sizing: border-box; can take some of the pain away, but it's new.

http://paulirish.com/2012/box-sizing-border-box-ftw/

That's all the tricky basics, really. Everything else is pretty self-explanatory, or tricky advanced stuff that's googlable once you get the basics down.
posted by fnerg at 10:12 PM on October 1, 2012


Others have written about the general concepts of CSS so I'm going to focus on something that still annoys and confuses me about CSS despite having written lots of it for many years: layout.

Layout is the hairy and tedious problem that all web designers eventually struggle with because once you play around with fonts and colors in CSS, you start wondering how you position the elements that you've created in your HTML document and then you realize that the various CSS references you have been jumping between don't mention anything like a layout property in the same way you have a font-family or color property. Odd.

The problem is the way CSS does layout, more specifically the incredibly unintuitive and generalized way you are forced to think about layout. In most other fields of visual design the medium you work with has physical qualities that makes layout grid based or free form.

Since web design has no physical medium and you are forced to design for a variety of devices, free form laout doesn't work. It's possible to give elements absolute positions but generally this is a terrible thing to do because the combinations of platforms, browsers and screen resolutions are too many to manage.

Unfortunately CSS doesn't have an intuitive built-in way of doing grid based layout either, forcing you to use floats, clears, CSS positioning properties and other building blocks that are incompatible with the mental models that you as a designer have acquired over the years. You know, concepts like the grid that are so fundamental to design that it's hard to think about design without them.

So you soldier on and sorta figure out how to bend CSS to your will, only to realize how unintuitive, fragile and device dependent the code is. That's when you give up on bare bones CSS and start looking at CSS frameworks.

CSS frameworks like Twitter Bootstrap make layout so much easier by offering building blocks - i.e. snippets of HTML/CSS code - just a level above floats and clears that allow you to create layouts that are consistent across all platforms, devices and browsers. Not perfect layout, mind you, just layout that is consistent from a visual aspect. Frameworks will save you hundreds of hours but more importantly they are much closer to the mental models of design layout that you might have. Frameworks aren't as good as a built-in CSS property (layout) would be, but currently they're the best thing we have.

So keep this in mind when you start writing layout CSS: (1) it's a broken and tedious process (2) use a CSS framework like everyone else.
posted by Foci for Analysis at 10:19 PM on October 1, 2012 [4 favorites]


I'll just talk about selectors, because that's the hard part; the actual style rules are easy.

Selectors

A selector is just a way of identifying one or more tags that might be1 in your web page. Selectors are made up of one or more "things", where each "thing" is one of these2:

1. The name of a tag (tag name) that might be in your document

For the HTML tag <div>, the tag name is div. For the HTML tag <p>, the tag name is p. For HTML tags with attributes, like <a href="#" title="foo">, the tag name does not include the attributes, so the tag name is a.

If you use a selector with a single tag name, you will be identifying every HTML tag with that name, no matter where it resides in your document.

2. A class that you might have applied to one or more tags in your document (prefixed with a .)

You can add a class attribute to (almost) any HTML tag, and write a selector that identifies those tags regardless of tag name by prefixing it with a period, like so: .myclass will identify <p class="myclass">, <div class="myclass">, <a class="myclass" href="#" title="foo"> or any other HTML tag that you have given a class attribute of myclass.

3. An id that you might have applied to one tag in your document (prefixed with a #).

You can add an id attribute to (almost) any HTML tag, just like a class attribute, and write a selector that identifies that tag. There are two differences: you can only put a specific id on one tag in your document3, and you use a pound prefix when writing a selector to identify it: #myid will identify the tag you've added id="myid" to, if you've added one.

That explains writing a selector using a single tag name, class or id to select the tags in your document with a matching tag name, class or id. A selector can also be a list of tag names, classes and/or ids -- separated by spaces -- to create a selector that gets applied only if there is an item that meets all the selection criteria.

The trick to reading the selector is to read it right to left, knowing that the rightmost "thing" will be the one with the tyles applied to it, and that each "thing" must be contained within all the "things" to its left:

Code: #mybox div .item {}

Brain: My styles will be applied to any tag matching .item inside any tag matching div inside any tag matching #mybox

So given these three potential structures:


<div id="mybox">
<div>
<p class="item">...</p>
</div>
</div>

<div>
<div>
<p class="item">...</p>
</div>
</div>

<div id="mybox">
<p>
<p class="item">...</p>
<p>
</div>


Our selector of #mybox div .item will match the innermost paragraph tag in the first example, but not the second or third, because only the first example has a paragraph tag that meets the selector criteria4.

Chained Selectors

One more fun thing: if (when reading right to left) spaces can be interpreted as "inside a tag matching", then a lack of a space can be interpreted as "and":

Code: #mybox div.item (note there is no space between div and .item)

Brain: My styles will be applied to any tag matching .item and div inside any tag matching #mybox

So given these two potential structures:


<div id="mybox">
<p class="item">...</p>
</div>

<div>
<div class="item">...</p>
</div>


Our selector of #mybox div.item will match the innermost div tag in the second example because it is has a tag name of div and a class name of item, but it will not match any tags in the first example.

1I say "might be", because you can write an entire style sheet full of selectors that don't actually match anything in your web page, and you won't get any errors. Instead, your selectors will match up with nothing, and you'll be left scratching your head wondering why nothing on your page is styled.

3There are other things that identify different states, like :hover, or different relationships, like >, but those come more easily if you understand the basics first.

3This is part of the HTML specification, not a CSS-related limitation.

4I cheated here and used the same id in two places, but just to illustrate a point; it is not the duplication of id that prevents the selector from matching the third example.

posted by davejay at 10:29 PM on October 1, 2012 [1 favorite]


The problem is the way CSS does layout, more specifically the incredibly unintuitive and generalized way you are forced to think about layout.
My personal a-ha moment with CSS came when I understood that CSS was designed for content that is “poured” rather than “laid-out”. Everything about it makes sense when you imagine HTML as a stream of things being poured into a page over time: the rules about lengths that let you do things horizontally which you can’t do vertically, the declarative syntax that is structured like a prediction about future elements, and the way that useful interactive content can be displayed before a page is fully done loading.

Imagine your HTML as a series of boxes being wheeled into a room through a narrow doorway, one at a time. You don’t know how many there will be so you can’t quite plan ahead. Instead, CSS gives you way to set up some rules you can use to arrange them as they come in, assigning appearances and behaviors while the room is still filling up. New box comes in, you look at your list of rules and figure out which ones are relevant (using the specificity rules that tylerkaraszewski mentions above) and send the box along.

I’m not sure if that’s in any way related to the part you’re having trouble with, though.
posted by migurski at 10:29 PM on October 1, 2012


CSS was hard for me, too. Not the syntax, but I had no idea what rules to apply to make a web page look even semi-professional. CSS-Tricks was a HUGE help, more so than any books I checked out of the library. The guy who runs it has put up well over 100 videos, including two series (first one: 1, 2, 3; second one: 1, 2, 3) where he converts a Photoshop mockup to CSS. The first series made CSS finally start to "click" for me. I still knew hardly anything, but I had some idea of how to go about building something, at which point I could look up the details and best practices. (Frequently my Googling would bring up incredibly helpful articles, code snippets, etc. on CSS-Tricks, actually.)

I never looked at books again after discovering CSS-Tricks, but prior to that, the best one by far I found was CSS: The Missing Manual.

CSS isn't conceptually rough once you're familiar with a couple basic ways pages can be laid out. (But it is other kinds of rough if you need your pages to actually work in all major browsers. Have fun!)
posted by randomname25 at 10:41 PM on October 1, 2012 [2 favorites]


Lots of good advice here. I'll add a few suggestions that may help:

The first is conceptual. I use a number of analogies to describe HTML to my students, but there's one that seems to stick best: think of HTML as the foundation and framing of a house. There's little color, and "design" is sketched out only in the most basic way. However, in order to have a sturdy structure it's vital that the walls are square and plumb, etc. In other words, your HTML code should validate (the equivalent of meeting a building code) before you apply any CSS. Many of the issues I find my students dealing with in CSS - "why doesn't the page look the way I want it to?" - are not to do with CSS at all, but errors in the HTML underneath.

Assuming that you have a good foundational structure in place, CSS can be compared to the decorative choices you make for the building: the paint, siding, etc. You can't "make a page with only CSS" any more than you can fling paint into empty air to create a house.

Keeping things basic, let's imagine we have the world's biggest paint bucket raised above this under-construction house. Let's tip the bucket and pour it over the house; the paint is entirely black:

body { background: black; }

The result is as ugly as it would be in real life. Almost everything on your page will be coated in blackness, because we're applying this CSS declaration to one of the most basic elements on the page, the tag that everything visible - the rest of your house - resides within.

To use your own English analogy of noun, verb etc: the body is the selector, the element that we wish to change (any element can be selected, as can classes, ids, etc). background is the property, the aspect of the selector that we wish to change. black is the value we have chosen to give to the property. Taken together, the property-value pair form a CSS declaration.

Let's switch to a pressure sprayer: something with a little more accuracy, but not much.

body { background: black; color: yellow; }

Now pretty all the text on the page (with the exception of links) will be yellow. We're still dealing with the big-picture, major construction stuff; let's finish by bringing out an ordinary paintcan and brush and use it to pick out some details:

body { background: black; color: yellow; }
p { color: white; }


We're getting more specific in our selector: being more picky about the element that we want to change. Just the paragraphs on the page will be turned white.

I find it useful to approach CSS that way: apply the big, standard rules first; basic colors, the fonts that most everything uses, etc. Then start crafting exceptions. I suspect you might be messing around with little details at this stage, and not seeing the big picture. (I'd also mention that you should be writing your styles from a linked style sheet, if you can: it's a best practice, and will make it very easy to apply a consistent appearance to other pages as you make them part of a site).

As I'm sure you're aware, there are many more possibilities for CSS, but getting these fundamentals is a good start. In addition the excellent resources others have suggested above, I'd humbly add my web development blog, which I use to teach my post-secondary students. I started it several years ago, after growing frustration with the lack of good, well-structured, and up-to-date web development documentation online (thankfully, the situation has improved over the last few years). You may find it useful.

I hope this helps!
posted by Bora Horza Gobuchul at 1:42 AM on October 2, 2012


For me, the cascading aspect of CSS took getting used to. Here's a decent description of it.

It would be helpful to understand where you are getting tripped up. If you post some of your bad attempts at CSS, that could help us see where you're getting stuck or what you're misunderstanding. Or perhaps you could talk us through your thought process in trying to solve a problem. Or if there are answers above that are over your head, tell us where you stop understanding. Sometimes the trickiest part is knowing the question to ask!
posted by heatherann at 1:58 AM on October 2, 2012


I've taught oodles of people how to write CSS and have written a few books on the subject. Learning CSS for me was very hard when I first started learning it 10+ years ago. The reasons have been pretty well defined in the comments above: although certain aspects are intuitive, as a layout language it is fundamentally flawed. Floats and clears were not designed to create grid layouts, but that is how we have to use them.

I'm looking back at your question and this phrase jumped out:
But as soon as I go to write some on my own, my brain goes "hrrrrrrrrr". This is a very weird feeling for me that's never happened before.
Part of the power of CSS is that it provides many options but this feels like a weakness when you are starting out: if there all these options which one is right?!

In order for you to write CSS naturally you have to feel very comfortable with the basics. It took me a few years to style a page without needing to consult a reference guide for the exact syntax.

Forget layout to begin with and just focus on understanding the many ways you could style a page with the following tags:

p
h1
h2
h3
h4
h5
h6

ol
ul
li

em
strong

There are a dozen tags there. Give yourself a simple exercise such as styling your shopping list or categorizing your 30 favorite books/movies whatever. Like anything else, learning CSS benefits from repetition. Start small and work your way up. You'll be fine!
posted by jeremias at 4:47 AM on October 2, 2012


This is what helped me:

First, I just mentally listed the differences in annotation that meant basically the same thing. Below are some examples.

html: < > = ""
Css: { } : ;


Then I figured out the basic structure:

thingbeingmodified

{ aspectofitbeingmodified: howtomodifyit; }

The thing being modified might be a font, the aspect being modified might be color, then how to modify lists the color(s).

My understanding is pretty basic but that got me over the hump of "what is this alien thing that isn't html!!??"
posted by Michele in California at 8:37 AM on October 2, 2012 [1 favorite]


I confess that every time I get stuck on something CSS related I go to W3Schools. It explains everything in a step by step way and with examples. It's quite basic, which is usually what you need when you're stuck.

But more important, every page has a 'try it' page where you can experiment with just a few specific elements.

Just for example, try this: CSS padding.

If you didn't understanding how the 'padding' settings worked before, in 3 minutes of experimenting on that page, you'll understand. You can make changes and see what happens quite instantly.

Also, you're not in the middle of an extraordinarily complex mish-mash of CSS where every thing interacts in an unexpected way with everything else. You can get an idea of how it is supposed to work, in a simple, uncomplicated context.
posted by flug at 3:23 PM on October 2, 2012


Also, one reason you may be more confused that usual is that CSS is really a form of object-oriented programming.

If you are used to thinking of things in a functional way, or as you say with basic HTML where one tag works on one bit of text in a simple and predictable way, the move to the more abstract world of OOP is pretty confusing and unsettling.

You're always worried about what properties your object has inherited from something else and what properties other objects will inherit from it. When you're working on one particular object or definition it is like there is no 'there' there--it just doesn't make sense all by itself.

Only when you put it in context of what it is inheriting from the higher-level objects and what the lower level-objects will inherit from it, does it make any sense at all. And that is a pretty difficult level of abstraction.

Part of the difficulty is everything already has a context (the 'parent' or higher-level object) and what you're typing in at any point is just modifying what the parent objects have put in place.

That means that there are tons of things that are just 'understood' and 'work like magic' because they are inherited, and until you get a good grasp of what those 'work like magic' things are and what they do, it is very, very confusing.

You might look for things like 'beginner's guide to object-oriented programming' for hints and background. One example.

FWIW I've been mucking about with OOP for more than 10 years now, and I have a master's degree in mathematics and not really afraid of abstraction, and I'm really just now starting to get somewhat comfortable with the concepts. Partly that's because I had a decades-long upbringing in more functional-style programming before that--we do get set in our ways--and no real formal instruction in OOP, just random mucking about 'for fun'. But really just now I'm starting to think, aha--that could have been done with an object-oriented approach more naturally.
posted by flug at 3:33 PM on October 2, 2012


Wow, heaps of answers! For audio visual learners, try Don't Fear The Internet (google it). Also, there are some good basic video tutorials done by Katrina of Pugly Pixel. Geared toward self learners who want to tweak their own blogs and websites, and she is a computer scientist - so she knows why what shes doing works. Good luck!
posted by jrobin276 at 4:08 PM on October 2, 2012


All of you are absolutely fabulous! I hit up W3Schools like my life depends on it. Also, I'm familiar with Don't Fear the Internet. Both are great resources, and I'm seconding them to anyone who comes behind me looking to learn. I've only made my way through a very small percentage of all this advice- I'm trying to read a bit at a time and let it sink in and so far I've had a couple really awesome epiphanies. A lot of it I already knew, but just hearing what I knew spelled out in a different way made it easier to make the step just after it. So, again, thank you.
And, to those of you wondering where I was just completely failing, I've been able to think about my confusion more clearly after reading some of your answers. Also, more advice is always beneficial and maybe if I lay it out here it can help someone down the line.
I wasn't having any trouble with the syntax, because it's a pretty concrete way of doing things.
selector {
property: value;
}
Yup. Got it. What really made me confused was that CSS is completely separated from content. I don't really know how to explain it, but with HTML you do things in order, like if you were physically writing it or drawing it. The order you put in HTML is the order your content is in. And there's a set way to do it: DOCTYPE, other metadata, followed by h1 header and then so on and so forth. But with CSS, that's not the case. It's more like, as someone mentioned above, a list of instructions that is applied to make the html look a certain way. And what links those two is the selectors, not any physical format of how the CSS is written. If you want an aspect of CSS applied to an element of html, then you list properties and values within the selector that matches. And then to get specific you can add classes, and then IDs.
What also confused me was that things could be self-named. That completely blew my mind. I'm still a bit confused with syntax for IDs and Classes.

fnerg, your explanation was just, great. maybe you can clarify one thing? you said:
apple.granny-smith {
color: green;
}
apple#in-my-lunchbox {
color: green;
}

In real-life CSS terms, would an apple be an element like p or h1 or something? And the n granny-smith [a class, yes?] is a self-named div class? Like, it would be something like

h1.home-page {
font-size: 200%;
}

All right, mods. I promise to stop thread-sitting now, and just take all the info in. [But if I'm off-base with any of my stuff here, please let me know somebody!]
posted by FirstMateKate at 8:45 PM on October 2, 2012


You're getting it. The dot indicates that what follows is the class name you made up and gave to some elements in your HTML. The octothorpe indicates that what follows is the ID name you made up and gave uniquely to exactly one element in your HTML.

And you don't need to specify the HTML element. These are all valid CSS selectors:

h1
h1.news
h1#top-banner
.news
#top-banner

Some of them only match h1 elements. The third one should match exactly one h1 element with the ID top-banner. The latter two may match any sort of element, but in principle, the last one should only match a single element (because IDs should be unique).

I don't see it mentioned above, but in addition to applying the same class name to multiple elements, an element can have multiple class names. So your HTML can say ...

<h1 class="reddish centered">

And then these CSS selectors would all match it:

h1
h1.reddish
.reddish
h1.centered
.centered

Incidentally, order does matter in CSS. Here are some simple examples.

One thing you might do to explore this empirically is right click a page you're viewing in Chrome and "Inspect Element." That opens up a tool with an "Elements" tab that will allow you to explore the HTML elements and see which CSS selectors are pertinent in the box on the right. Click the magnifying glass on the left side of the bottom bar and then click on some part of the original page. In the box on the right, you should see what styles are being applied to the element, based on which selectors. And on a lot of pages, you'll see some styles being overridden because of the ordering deal I mentioned. You can use this exact same tool in Safari, but it has to be specially enabled. In Firefox, a similar tool is called Firebug.
posted by Monsieur Caution at 10:40 PM on October 2, 2012


@FirstMateKate, Yep, you've got it.

Another way to think of it is that the CSS declarations are floaty balloons that could be anywhere above the concrete structure of your HTML. Selectors are strings that you can use to tie them down to arbitrary places in the page.
posted by fnerg at 4:16 PM on October 3, 2012 [1 favorite]


In real-life CSS terms, would an apple be an element like p or h1 or something? And then granny-smith [a class, yes?] is a self-named div class?

Yes, except that a div is also an element like an h1. Just delete that word from your sentence and you've got it exactly right. :)

h1.home-page {
  font-size: 200%;
}


Yes, this is good. That rule will apply to any h1 with the class "home-page". It would not apply to <h1> or <p class="home-page">.

Also remember that CSS can see the hierarchy within your HTML document and use that to target things. For example, I could trump your h1.home-page rule by getting even more specific:

h1.home-page {
  font-size: 200%;
}
body.splash h1.home-page {
  font-size: 100%;
}


The second rule will supercede the first rule when h1.home-page is inside a body element with the "splash" class. The more specific rule always wins. As you might imagine, this is awesome when you want to target links in the main content area but treat links in the sidebar a little differently. You don't have to put a class on all of the links, you just have to create a hierarchical rule that cares about which div the link lives in (div.main a vs. div.sidebar a).

A lot of CSS thinking is about sorting things into more and more precise piles of stuff. You can see this being set up in the HTML of the page this question is on. From the source code:

<h1 class="posttitle">#wrapper { smart-level= 0% }<br>
    <span class="smallcopy">October 2, 2012 12:12 AM &nbsp;
        <a href="/225758/wrapper-smartlevel-0/rss"><i class="feedicon"></i></a>
        <a href="/225758/wrapper-smartlevel-0/rss">Subscribe</a>
    </span>
</h1>


And some of the CSS:

.posttitle a {
  color: #666;
  font-style: normal;
}


As you know, links on MeFi are blue by default. Here we see an exception for links within post titles. See that working in the Subscribe link at the top of the page?

One last thing. Check out these two rules from this page's CSS:

.posttitle {
  color: #DDD;
}
h1 {
  color: #069;
}


Why is the h1.posttitle on this page grey (#DDD) rather than blue (#069)? Because the element rule gets trumped by the more specific class rule.
posted by heatherann at 9:08 AM on October 7, 2012


« Older In Canada, what kind of (gover...   |  This is happening in Californi... Newer »
This thread is closed to new comments.