Which is more beneficial: incorporating a ready-made rule for every CSS style or crafting your own rule (OOCSS)?

Learning about Nicole Sullivan's concept of Object-Oriented CSS (OOCSS), I discovered the idea of using pre-existing basic building blocks as classes and then customizing them to suit individual needs rather than starting from scratch each time. The OOCSS principle draws inspiration from reusing existing code, much like how you wouldn't rewrite the Java Math class every time you need a specific mathematical function.

While I find this approach appealing in theory, applying it practically poses some challenges for me. If anyone has more resources on OOCSS that could shed light on its benefits and criticisms, please share them!

Take my current stylesheet for example:

.heading {...} /* applies to all headings */
  .alpha   {...} // specifically for h1 
  .beta    {...} /* specifically defined styles for h2 */
  .gamma   {...} /* unique styling for h3 */
  .delta   {...} /* customized changes for h4 */
  .epsilon {...} /* tailored look for h5 */
  .zeta    {...} /* individualized design for h6 */

The initial selector is for universal heading properties like font-family and

letter-spacing</code, while each "subclass" contains distinct attributes such as <code>color
and font-weight. Placing these subclasses after the main .heading indicates that conflicting properties will be overridden by those in the subclass. To style a Heading 1 element, one might write:

<h1 class="heading alpha">Contact Me</h1>

What if, hypothetically,

.heading {...}
  .alpha {
      extends: .heading;
      ...
  }
==============================
<h1 class="alpha">Contact</h1>

If normally heading alpha elements are aligned left, how would I center this specific instance? Instead of adding another class, perhaps inline styling or simply including .alpha {text-align: center;} at the top of the Contact page could suffice without cluttering the HTML with excessive classes?

Answer №1

OOCSS is not about solely copying CSS snippets from other sources and only creating new rules when it's something completely unique. The main goal is to abstract your styles as much as possible. Specific styles are less reusable, leading to writing more CSS overall.

Think of OOCSS like programming classes - instead of separate car and truck classes with redundant methods, create a vehicle class with the shared functionality. Similarly, use CSS classes as mixins for common styling tasks.

Consider visual abstractions when defining classes. For instance, if most sections on your site have bordered boxes, create a base class like .bordered-box and mix in additional styles like color and width as needed.

View your CSS classes as tools in your toolbox for building a website, rather than just properties to make elements look a certain way. Avoid creating classes like "ital size-medium sans-ser txtJ med-height dark-blue", as this blurs the line between visual objects and CSS properties - it's better to stick to defining visual concepts in your classes.

Answer №2

In my opinion, relying on classes like .txtC or .dark-blue goes against the core principles of CSS. The beauty of CSS lies in its ability to completely transform the appearance of a website with just a simple change of stylesheet.

Consider this scenario: let's say you suddenly decide that all your headers should be red instead of blue. Instead of a quick update in your CSS file like .header { color: red }, you would have to manually hunt down and replace every instance of the dark-blue class with red in your HTML. Alternatively, you could tweak your CSS to dark-blue { color: red; }, but then the class name becomes misleading.

If we start adding unique classes for every styling variation imaginable, we risk reverting to the days of inline styles and excessive use of align="center" attributes.

Instead, if we embrace a more "object-oriented" approach to CSS, we could define a general rule like .header for all headers and then introduce additional specificity when needed. For instance, a specific font color for the header on the homepage can be achieved by creating a new rule like .header.home { color: cyan; }. This way, our CSS classes and IDs accurately reflect the content they style, rather than just focusing on visual presentation.

Answer №3

When it comes to maximizing the potential of your CSS, "Object-oriented CSS" is a valuable design pattern that shares similarities with Jonathan Snooks' SMACSS.

Whether you prefer OOCSS or SMACSS, the core concept remains the same: creating versatile UI components like the nav abstraction. These components can then be customized further by adding extra classes or encapsulating them within another element. Additionally, custom CSS rules can also be applied using IDs or semantic classes.

A promising new CSS framework called Cascade Framework is built on this foundation. It promises optimal performance, flexibility, and modularity while maintaining a minimal footprint.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

ReactJS not displaying the class effect as intended

When using the react zoom pan pinch library, I am trying to set the height to "100%" for TransformWrapper and TransformComponent. Interestingly, it works perfectly fine when done through Chrome inspect, but when attempting to add a className or use style={ ...

Is there a way to eliminate unknown white gaps in the content?

I have encountered a very perplexing issue. When accessing this site on Safari, an additional 4-500px of scrollable whitespace is added. This is clearly not the intended behavior, but I am struggling to understand what is causing this space :S Upon inspe ...

Switch the image source when hovering over a text menu

Currently, I have been using the following code to switch between images. However, what I actually want to do is change the image when hovering over the title link of the image. onmouseover="this.src='Images/img.png'" onmouseout="this.src=' ...

There is a single div sandwiched between two others, with each of the surrounding divs reaching the edge of the browser

Require a small space between the middle div and the two on each side. The middle bar should have a fixed width. Here is my attempt so far, but it seems messy: <!DOCTYPE html> <html> <head> <style> #container { width: auto; ...

What is the inner workings of CSS?

I'm curious about the inner workings of CSS. Does the HTML get interpreted before CSS, or vice versa? Or does it all apply as soon as the browser has constructed the DOM? I would appreciate a detailed explanation on this topic. ...

How to keep an image anchored at the bottom of the page without overlapping other content

I'm trying to have a logo image stay fixed at the bottom of a navigation drawer, but when I use absolute positioning and set it to the bottom, it overlaps with the list items on shorter devices. When the scroll bar appears due to shrinking the browser ...

Adding the children of JSON objects to every individual div element

How can I add each day's players [day-1, day-2, day-3, day-3] wrapped in a <span> into the .card-body section as required? The goal is to load only four card-body. var vehicles = { "day-1": { "player-1-1": "Ford", "player-1-2": "BMW ...

What can be done to address columns overlapping when sidebar is activated?

Excellent https://i.sstatic.net/gwOI8.png Terrible https://i.sstatic.net/4f637.png The first image labeled as 'Excellent' shows that the card divs do not overlap, but in the second image when the sidebar is active they do. I attempted to cha ...

the css stylesheet fails to load properly within the Django application

While using static files in my Django app, I encountered a peculiar issue: specifying body{ } in the CSS file can alter the body's attributes, but using the div's id or class name does not affect the div's attributes. Here's an example: ...

The grid is out of alignment, causing elements to jump to the next row

After taking an online course at TreeHouse, I used the provided HTML & CSS code and made some adjustments to create a layout with 10 columns instead of the original 12 within a 1000px container. The columns were converted to percentages to fit my needs. I ...

Discovering descendant div elements

I've been conducting some research, but I'm struggling to find a specific answer for this. Here is the HTML code snippet: <div class="collapsingHeader"> <div class="listItemWrapper"> <div class="itemWrapper"> ...

Adjusting the width of an image in Safari

I just launched my website, but I encountered an issue with the image size in Safari. In my CSS, I set the width like this: img { width: 450%; } Here is the site: I can't figure out why the images display correctly in Chrome and Mozilla, but ...

Adjusting the size of an image based on the size of the window

I'm currently working on my first website project. I have successfully implemented a large image banner, however, I am facing an issue with setting its height. Whenever I try to adjust the height using percentage values, the banner disappears. My goal ...

What are the steps to create a scrolling effect for the menu buttons on the mobile version of

When accessing the mobile version of Facebook on a handheld device, you will notice a menu with various options like "About," "Photos," "Friends," "Subscriptions," "Map," and more. This menu is designed to be slideable on your mobile device. Using HTML, ...

"Encountering a Challenge with Setting Up Forms on

I've recently started learning to code and I'm facing an issue with my form appearing stretched out. You can view it here: I initially thought it was due to margins, so I increased them. Then, I tried adjusting the width to 50%, but that didn&ap ...

Aligning a div element horizontally

I'm having trouble aligning the div element with the .slider class horizontally. The margin: 0 auto; property doesn't seem to be working. Additionally, I would like to know how to make the slider image responsive. /* CSS Document */ .header { ...

Adjustable Columns in Bootstrap Table

After searching, I came across this documentation on how to make columns resizable in bootstrap tables. However, I am struggling to figure out how to actually implement this feature with an HTML table. Can someone please provide a clear example of how to ...

Steps for stopping the sass --watch function on a specific folder

Successfully got my SASS up and running with the help of fantastic documentation available everywhere. The guide I followed was http://sass-lang.com/guide. sass --watch myfolder/css Running a specific command worked like a charm, enabling every change in ...

Why did the CSS rendering suddenly come to a halt?

I am facing a confusion with EJS. When I make a post request, EJS renders my CSS properly. However, when I try the following code snippet: exports.resetpassword = async (req, res) => { const {id, token} = req.params; const user = await LoginMo ...

Struggling with modifying background color in Vue.js?

My intention is to make the landing page background color orange, but I'm encountering an issue where all pages end up with the same color. I attempted to use scoped on the landing page to target only that specific page, however, it resulted in the e ...