In my head, I've always known to use classes over inline styles for any project. But are there any articles/postings/blogs defining the pros/cons of each? I'm in a debate about this, and I cant seem to find the blog post I read a long time ago about this.
相关问题
- Adding a timeout to a render function in ReactJS
-
Why does the box-shadow property not apply to a
- Add animation to jQuery function Interval
- jQuery hover to slide?
- Issue with star rating css
Assuming that you are using external stylesheets, an additional benefit on top of those previously mentioned is caching. The browser will download and cache your stylesheet once, and then use the local copy each additional time it is referenced. This allows your markup to be more compact. Less markup to transfer and parse means a more responsive feel and better experience for your users.
I can think of only two situations where inline styles are appropriate and/or reasonable.
If inline styles are programmatically applied. For example, showing and hiding elements with JavaScript, or applying content specific styles when rendering a page (see #2).
If inline styles complete a class definition for a single element in cases where id's are neither appropriate or reasonable. For example, setting the
background-image
of a element for a single image in a gallery:HTML
CSS
For this thread to be complete, it is worth mentioning that inline styles are the only way to go in GMail when you create HTML+CSS emails.
For detailed information see: http://www.email-standards.org/clients/gmail/
If the choice was there, my first preference will be classes/other selectors. However, there are situations where inline styles are the only way to go. In other situations, just a CSS class by itself requires too much work, and other types of CSS selectors make more sense there.
Suppose you had to zebra stripe a given list or table. Instead of applying a particular class to each alternate element or row, you could simply use selectors to do the job. That will keep the code simple, but it won't be using CSS classes. To illustrate the three ways:
Using only class
Using class + structural selectors
Using inline styles
The second way looks the most portable and encapsulated to me. To add or remove stripes from any given container element, simply add or remove the
striped
class.However, there are cases where inline styles not only make sense, but are the only way to go. When the set of possible values is huge, it will be stupid to try to make classes in advance for each possible state. For example, a UI that allows the user to dynamically place certain items anywhere on the screen by dragging. The item will have to be positioned absolutely or relatively with actual coordinates such as:
Surely, we could use classes for each possible position the div can take, but that's not recommended. And one can easily see why: