Markup Practices and Style and Conventions Examples
Namespace and scope
We play nicely with others, so we namespace all our classes to avoid any conflicts. Therefore, we should properly prefix our classes unless we have a specific reason to use the global namespace.
Example:
h1 { margin: 1em; // global namespaced. } .myContainer h2 { margin: 1em; //locally namespaced. }
Component classes vs. Style classes
In our markup, we have Javascript and CSS acting on HTML elements simultaneously. It is tempting to use a single class to use for both styling and in the Javascript.
Example:
Person 1 has created a small webapp that allows reordering of paragraphs on a page.
HTML:
<p class="movable">Movable item #1</p>
CSS:
.movable{ font-size: 2em; }
Javascript:
demo.init = { selectors: { movableItem: ".movable" } }
Person 2 picks up the code later to add some titles to the webapp. He likes the paragraph style, so he re-uses the classname for a header:
HTML:
<h1 class="movable">Our Tech Demo</h1> <p class="movable">Movable item #1</p>
What happens now is the header added becomes movable which adds / breaks the functionality of the webapp since the header element was not intended to be part of the interaction!
Moral of the story, use separate classes to separate the Javascript interaction from the styling.
Example:
HTML:
<h1 class="style-movable">Our Tech Demo</h1> <p class="selector-movable style-movable">Movable item #1</p>
CSS:
.style-movable{ font-size: 2em; }
Javascript:
demo.init = { selectors: { movableItem: ".selector-movable " } }
Class naming conventions
Follow the convention stated in the Class Name Conventions document.
Prefixes:
- Demo Selectors:
demoSelector-*
- Demo Style:
demo-*
- Fluid Selectors:
flc-*
- Fluid Style:
fl-*
Basic Demo Markup Structure
HTML
- Comments are nice, especially for large blocks or mark-up that isn't self explanatory.
- DOM selectors first, styles following. i.e.
<p class="flc-movable fl-movable demo-disabled">
- Wrap markup inside a container with a properly name-spaced class or ID.
Example:<body class="demo-componentName-container"> ... </body>
or
<body> <div class="demo-componentName-container"> ... </div> </body>
CSS
- Avoid using global namespaced styles. If using global styles, commenting the style is recommended.
- Add comments to CSS if the reason for properties is not clear. i.e. If changing the inherited margin from 2px to 0px may not be abundantly clear. Or if there are styles specific to browsers or bugs.
Dealing with Javascript
- to be written.
listReorderer-good.html
listReorderer-poor.html
listReorderer-good.css