"Modular" CSS

Hi everyone,

I’ve been doing a lot of CSS work lately where I have these sort of modular components which needs to be dropped in everywhere and anywhere.

Now, a problem that’s probably obvious is that since it inherits styles from whatever it is placed in, there is often the need to “reset” a lot of things.

So, I’m looking for techniques to help make these modules stay more modular and not be affected as much. Any tips? It doesn’t have to be a complete solution since I know there isn’t a super clean one (other than putting all styles on the inner most elements, but then that eliminates the “cascading” part of CSS… which isn’t very good).

To clarify what I’m talking about, say I have something like this:


// CSS
.module { font-size: 1.2em; }

// HTML
<p class="module">Test</p>

If I then want to put that “module” in another area, like:


// CSS
.block { font-size: 1.6em; }

// HTML
<div class="block"><p class="module">Test</p></div>

All of a sudden module has a font size of 19px instead of 12px, so I have to add:


.block .module { font-size: .6316em }

to get it back to 12px.

That’s just how EM’s and % work – they multiply by each-other parent to child… as such 1.6 * 1.2== 1.92

My question would be why are you setting it larger on .block if you don’t want it larger on block, why would you be setting it larger than it’s declared on body when it’s a PARAGRAPH, etc, etc…

Of course if 1.2em is giving you 12px at default/96dpi, it sounds like you bought into that idiotic 62.5% LIE on body… where 1em == 10px – which is 100% bullcookies since not all systems start at 16px in the first place.

The tricky part of that is it reduces the ability of the module. And even in that case, I’d still have to “reset” the module if I put it in something that overrode some styles.

That isn’t a really good example, it was just a quick example. I know that’s how it’s meant to work, but I’m looking for ways to mitigate it.

A more appropriate example is that in one project I’m working on has a “name card”, which is a block that is a bunch of fields that identifies a user (like a profile). I want to use that name card, looking exactly the same, in a number of places. One place I use it in has almost no styles on it, so the card works just fine. However, other places I use it has lots of styles applied to it, so I have to add more styles to the card in that specific location to negate the styles of it’s container.

Font-size was just something I chose because it’s simple to understand, but everything is affected: margin, padding, font-weight, color, etc.

That SOUNDS like treading perilously close to using your classes in a presentational manner – like that OOCSS nonsense or people doing things like class=“centered redbox bigfont”… Which basically defeats the point of using CSS in the first place.

Though we’re guessing wildly because you are using snippets instead of full markup with meaningful content – but that’s one of the problems inherent to many example codes and snippets as without real content we can’t (or at least shouldn’t) say what the right markup is, much less what CSS to apply to it.

Man how I’ve wished many a time that css had a way of stopping the cascade from flowing into certain blocks. As you mentioned, a reset is the solution - outside of using an iframe.

Commonly a reset class is setup that can be applied to all of your components/widgets. This would set all possible css properties back to a default. The most robust resets for this employ liberal use of the usually discouraged !important declaration. But if you control all the css for the site you could get away with not using !important by keeping the specificity for all general page styles low and then employing a reset for your components that uses a higher specificity (eg. html body .component).

The notes here offer some good points on the matter.
http://dharmafly.com/bcb4/
and here’s a robust solution that uses !important - but it may be overkill for what your doing? It’s definitely not clean and simple.
[URL=“https://github.com/premasagar/cleanslate”]https://github.com/premasagar/cleanslate

Your example is fine btw. I think it properly shows what your getting at.

deathshadow60, bemoaning commonly used techniques (62.5%) and under estimating the intelligence of the OP (check out his join date) is not at all helpful. While use of ‘centered redbox bigfont’ is bad, samanime didn’t use anything like that in his posts and didn’t at all ask us to tell him what ‘the right markup is’. Also, having opinions is fine (statements like ‘LIE’ and ‘nonsense’ are very strong), but if your going to give them, at least give some backup as to why you have them - a link to a good article that will enlighten us perhaps?

Great first post, BryceBubbles. Welcome to Sitepoint.

Those are some really good notes. The idea makes sense. Luckily in this project, I only have two modules, so doing a reset isn’t that big of a deal. I normally do a manual reset where I explicitly counter the CSS that affects my module. Their widget parts sounded like they were basically saying to create an overall “default value” set of all values. That’s not a bad idea and I may explore that, as it would be a little cleaner (and perhaps more flexible).

DS, I understand why you think I’m starting to talk about OOCSS, but I’m not. =p What I’m talking about is a block of HTML that represents a specific object (think more widget than OOCSS object). This HTML should be rendered the same regardless where it is.

Here would be a more complete example (I can’t actually paste what I’m working on):


// CSS
.namecard {
  font-family: Arial, Helvetica, sans-serif;
  color: #00CBDF;
  width: 300px;
  padding: 5px;
  margin: 10px;
  border-radius: 10px;
  background: #E0E0E0;
}

.namecard h2 {
  font-size: 2em;
}

.namecard li {
  list-style: none;
  margin: 2px 0 2px 4px;
}

.namecard li a {
  color: #FF0;
  font-weight: bold;
}

// HTML
<div class="namecard">
  <h2>Bob Smith</h2>
  <ul>
    <li>Location: <a href="#">Nowhere</a></li>
    <li>Favorite Color: <a href="#">Blue</a></li>
    <li>Cookies: <a href="#">Yes</a></li>
  </ul>
</div>

If you loaded that HTML and CSS, you’d have a specific look for that specific HTML. Now, say I want to use that name card in multiple places on a page, contained by different parents. Since those different parents have different CSS applied to them which cascades into the namecard, changing the presentation of that card in that location. Since I want that same code and CSS to always look the same, I then have to reset (or negate) the CSS to bring it back to the present state.

That’s what I’m talking about. =p

Thanks, been reading the sitepoint forums for years, but felt I could add something this time.

Yeah resetting all possible properties could be overkill for your situation (and is for most), but it will make the component more robust. You can set it up once and know that no matter where it’s put or what other page styles change you (or a fellow dev who’s not as familiar with whats going on) don’t have to worry about it breaking. I know I’m definitely all for that.

Kind of assumed samanime could handle my approach to questions by now – and just because something is “commonly used” doesn’t make it any good - 62.5% == 10px being a perfect example of short-sighted nonsense… Since for example on my old WinCE phone I stopped using three years ago 62.5% would have worked out to 8px (IE rounds 7.5 up), my current workstation and most every desktop I’ve owned the past decade and a half it works out to 12 or 13 px (12.5 rounding being browser dependant) and on my HTPC it ends up being 20px. It’s called the “system metric” – 72dpi… 75dpi… 120dpi… 144dpi… Not every computer used the 96 dpi the 62.5% nonsense assumes everything uses… In fact, attempting to maintain a PX to EM ratio defeats the entire point of declaring EM in the first place!

CSS is only as good as the markup it’s applied to – and it SOUNDS like his problem is with the parent element, leading me to question how those parent elements are built both in markup and CSS. CSS without the markup it’s applied to (including all parents) is pretty much gibberish.

Go into windows 7, control panel -> personalize -> display… default page is “make it easier to read what’s on your screen”
Smaller - 100% == 96 dpi… so Opera and IE default to 16px == 1em
Medium - 125% == 120 dpi… so Opera and IE default to 20px == 1em
Larger - 150% == 144 dpi… so Opera and IE default to 24px == 1em

In XP - display properties -> settings -> advanced -> general -> dpi Setting
Normal Size (96dpi) == Opera/IE 16px == 1em
Large Size (120dpi) == Opera/IE 20px == 1em

Windows 3.x during device driver installation, choose “Large fonts / 8514” option on the driver if available, and you get the equivalent of the 120dpi setting… Which I’ve been running as my default choice since Win 3.0 introduced it for the 8514 graphics modes (though I had a dual head targa board capable of the same resolutions)

So 62.5% does not always equal 10px… which usually means layouts that rely on that relationship break disastrously – defeating the entire POINT of using %/EM in the first place… at which point you might as well just say font-size:10px on body for all the good it does you… Though naturally with webkit and gecko ignoring the system metric by default with their whole “accessibility, what’s that” attitude – it’s not too surprising you still get people who can’t grasp the concept. (even though it’s usually easy enough to force the change in those browsers).

Though really I’m still trying to decipher samanime’s posts – its’ not like padding or margin default to inherit; they don’t cascade down in – or are you doing something like “.parentElement div {}” in which case the answer is simple… Doctor, doctor, it hurts when I do this…

To me it really sounds more like a flawed approach to applying CSS and/or building the markup – you don’t want them to cascade, don’t apply them that way… Though again I’m not seeing enough code to weigh in fully on that; It just SOUNDS like broken sitebuilding methodology… I mean, if you have a section inside the same parent you want to style different, you DIVide it out to be targeted separately…

I’d really have to see what it is that div.namecard is being put into – though it really sounds like the markup itself could be flawed and/or at fault in terms of how the elements are being nested. Basic CSS, you don’t want something hitting all child elements, target the children directly instead of the parent.

Though it could also be as simple as a specificity issue; second copy of the declaration with the parent ID prepended and/or !important could be all it needs.

Thanks for the extra info on the 62.5% issue DS, I’ll look into it more. Just curios, how do you go about defining your font-sizes?

I never saw the point of this being to always have the em value equal to a specific px value (impossible as you have mentioned), but as a help to the developer by keeping the font-size declarations simple while using ems. A designer specifies certain font sizes to use as a base, and in stead of having to remember the calculations you just divide by 10. Inheritance and the cascade make this not perfect, but I’ve always found it tidy. I’m open to better solutions though.

The point here is that we don’t want to have to know what it’s being put into. div.namecard should be able to go anywhere and still look the same.

Yes this (in short) is the answer.

I do this crazy thing where I declare the font size that 90%+ of the elements on the page are going to actually USE… that way I don’t have to keep saying it every time there’s a new element not inheriting it… generally that’s 85% for arial,helvetica,sans-serif (the most legible combination of size and family stack I’ve found) though I go 100% for serif fonts (as smaller the serifs make it hard to read) or for fonts with smaller X-heights and M-widths (like say… verdana, which usually looks like **** to me no matter how you size it). I use 85% and not 82.5% because it rounds up to 17px instead of 16px for 120dpi systems, while still delivering 14px to 96dpi and 12px to 72/75 dpi… It’s the ideal across all of them… in arial or helvetica. Other faces… well…

It’s one of the issues I have with the 62.5% – it’s a useless size so you’re wasting time re-declaring the size on everything anyways… kind of defeats the point of CSS – only time I’d be changing the size would be on headings – numbered heading tags, legends, captions, and occasionally TH or standouts/CTA’s… or when something gets a different font-face. (like say… PRE/CODE/SAMP)

That’s why most always the font declaration on body in my code is:

font:normal 85%/150% arial,helvetica,sans-serif;

Which I’ve never understood how it “helps” – since you end up wasting time restating your font size on everything over again that way; It’s more work for something you should just let happen. Why wouldn’t you SHOCK state on BODY what everything except your headers should be using for a size? I realize some designers seem to love to piss all over accessibility and make every blasted paragraph in every single section of the page a different size; my rule for that is DON’T! (unless you have px metric fonts shoved down your throat by a px width column, the footer on a 100% min-height, or an image interaction)

I’ve always found it messy for the reasons I just outlined – restating things you shouldn’t have to when you could just set it once on BODY – and as to “calculations” you just go “I want it larger”… usually increments of 10% or 20% are ideal. See why most of my H2 end up 140%, H3 at 120% and the very very rare H4 being 100% and just bold. (I have this rule, if you end up at H5, in all but the rarest cases something’s probably wrong with your document structure)

… and that’s the problem – if your putting it into something that’s futzing with it, the problem isn’t with div.namecard it’s with what you are putting it INTO… since a parent container of a section should NOT be setting anything that would screw with it in the first place if you have anything remotely resembling a logical document structure! That’s why I’m pointing the finger at what it’s being put into and not the element itself.

I haven’t looked into them in detail but CSS3 rem font-sizing could be useful for avoiding the compounding issues and allow elements to be nested anywhere (almost as though they were specified in pixels) but still be dependent on the root element for their scaling.

Yeah I see where your coming from sure - sometimes the problem could be solved by reorganizing the way styles are declared further up - and that’s fine while your in control of the code for the whole site, which samanime probably is. But I think for a reusable component I’d rather make sure that as many properties as possible are set to a specific default (at a higher specificity than normal). That way no matter where it’s placed in the site - or in some other site down the track for that matter - I wont have to worry about it being changed by it’s surroundings.

Paul O’B: Cheers, I hadn’t heard about the css3 rem (root em) unit, that’ll be very cool down the track. Unfortunate that IE7/8 will be around long enough to make using it a little unfeasible for quite a while. Sweet if you don’t have to worry about them.

Funny thing about REM is, apart from being a suck-ass band, PT is supposed to deliver the same functionality since points should obey the system metric – if legacy IE didn’t have it’s head up it’s ass about resizing PT, it would be the better choice that would work RIGHT NOW. With IE7/later being the norm and using a pathetically half-assed attempt at Opera style resizing, maybe it’s time to look at PT again.

Which is part of why I stuck with PT as long as I did, and still keep looking back at it every now and then. I mean, if the point is to have a font that dynamically adjusts to the system metric, PT already does that in FF (hell, it’s the ONLY metric that does in gecko thanks to it still being Nyetscape 4’s sweetly retarded cousin), Opera, and IE. Though as always Webkit goes "accessibility? Never heard of it!!! System metric? What the devil’s a system metric?… now I’m not saying webkit on Operating Systems that have mechanisms in place for accessibility is like a trip in the wayback machine to Nyetscape 2… No, wait… that’s EXACTLY what I’m saying.

Which is why it’s shocking it works so well on mobile – were that as much effort was put into desktop versions.

Ha! Nice one! I’m not much for Physical Training, but I may have to look into PT…:rolleyes:

Anyway, I was just having a quick muck around with rem vs em just now and I checked out your body font declaration deathshadow and you’ll be happy to know I’m sold (and this discovery does make rem pointless). I can’t believe I’ve been so blind!

As you said, if you set the body to the base size you want most text on the page to be (usually stuff inside p/li right), the compounding issue becomes a non-issue, and you hardly have to set the font-size on anything. I’ll never use 62.5% again!

So after my spout at you earlier about opinions - cheers for putting yours forward! Sometimes we need to be kicked into letting go of our silly old ways. Check it out people.

I don’t think its pointless but I’m not completely sold on its usefulness.

I can think of a few cases where it will be useful such as nested lists or for setting certain headings to be based on the html default no matter where they are found. But, much like Jason said I tend not to apply font-size rules to containers to start with so it’s not much of an issue for me either. I guess if you were working on an existing clients site then it could be useful if they have structured the site badly. You don’t always get to work on nice clean code.:slight_smile:

Yes applying font-sizes to containers in general is an easy way to cause problems for yourself. But by setting the font-size you want to apply to your main copy on the body and leaving/setting p/li (which for me are pretty much always the same) at 1em - nesting things inside lists won’t cause a problem. Headings should then also never be inside anything that would change their size either. Hence rem isn’t really needed.

I created a jsFiddle for those who like examples.

[ot]@BryceBubbles
You may find my font size comparison page helpful in determining which metric to use, and the different issues between named, %/em, pt and px…

http://battletech.hopto.org/html_tutorials/fontCompare/template.html

Pay particular attention to how on 120dpi systems Opera and IE obey it for %/em and pt, while FF obeys it for pt but not %/em, and webkit goes “well what’s that then?”
[/ot]

Thanks for the link deathshadow. It’s quite a read, but very revealing. It’ll take me a while and a couple of reads to really get my head around it I think. Anyway yes we’re off topic, so I’ll leave it there.