While using this method on our projects, we noticed our class attribute was getting extremely cluttered with a variety of spacing classes on a single element. Here’s an example:
您需要 登录 才可以下载或查看，没有帐号？立即注册
As you can see, there’s an overload of spacing-based class names littering the codebase. Scanning over this code with your text editor or devtools can become overwhelming. So how can we simplify this?Mark and I discussed a possible solution for this problem and came up with something like this:
We decided to use a custom attribute called `spacing` to separate our spacing classes from the stylistic classes. Our spacing classes only handle margin top while our stylistic classes set the background, borders, padding, etc. This ensures all the classes applied to an element are specifically for visual styling whereas any value in the spacing attribute is specifically for our vertical spacing throughout the project.
Here is a snippet of our .spacing.scss. We are using include-mediato handle our media queries.
In this snippet, we are defining our spacing variables as well as setting our default CSSrulesets. we use a complex CSSselector to provide two collaborative, abilities. First, the ‘begins with’ selector is used to allow a default spacing to be set. Then using a wildcard match we can override that spacing on specific breakpoints using our custom `large()` syntax”. In some cases the spacing can vary from screen size to screen size. Following our default classes, we have a CSSruleset to target spacing at different screen sizes.
Following the default spacing classes, we’re using CSSselectors to target any value in our attribute. If we don’t define `xsmall-xlarge` then it won’t be available. This is to keep the generated CSSsize small and reduce extraneous code that we may never even use.
Putting it all together
The browser reads the example like this:
Some may ask, why aren’t you using “data-” to define your custom attribute? This is still up for discussion here on the development team. Sure, we might run into some issues further down the line, but that’s as easy as doing a `replace all` to fix our spacing attributes. We’re testing this method with one of our current projects and it’s going pretty smoothly. Does adding “data-” to our custom attribute really matter nowadays? I’d like to hear your opinions.
- Give each direct child of the article element a margin-top of 14px on small screens and 20px on large screens.
- For small to medium screens, give the direct child elements a margin top of 10px
- On large screens give the direct child elements a margin-top of 60px
下一篇：Personalized Group Recommendations Are Here