-
Notifications
You must be signed in to change notification settings - Fork 2
/
3-create-reusable-css-with-mixins.html
52 lines (43 loc) · 2.3 KB
/
3-create-reusable-css-with-mixins.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<!-- Create Reusable CSS with Mixins
In Sass, a mixin is a group of CSS declarations that can be reused throughout the style sheet.
Newer CSS features take time before they are fully adopted and ready to use in all browsers. As features are added to browsers, CSS rules using them may need vendor prefixes. Consider box-shadow:
div {
-webkit-box-shadow: 0px 0px 4px #fff;
-moz-box-shadow: 0px 0px 4px #fff;
-ms-box-shadow: 0px 0px 4px #fff;
box-shadow: 0px 0px 4px #fff;
}
It's a lot of typing to re-write this rule for all the elements that have a box-shadow, or to change each value to test different effects. Mixins are like functions for CSS. Here is how to write one:
@mixin box-shadow($x, $y, $blur, $c){
-webkit-box-shadow: $x $y $blur $c;
-moz-box-shadow: $x $y $blur $c;
-ms-box-shadow: $x $y $blur $c;
box-shadow: $x $y $blur $c;
}
The definition starts with @mixin followed by a custom name. The parameters (the $x, $y, $blur, and $c in the example above) are optional. Now any time a box-shadow rule is needed, only a single line calling the mixin replaces having to type all the vendor prefixes. A mixin is called with the @include directive:
div {
@include box-shadow(0px, 0px, 4px, #fff);
}
Write a mixin for border-radius and give it a $radius parameter. It should use all the vendor prefixes from the example. Then use the border-radius mixin to give the #awesome element a border radius of 15px.
- Your code should declare a mixin named border-radius which has a parameter named $radius.
- Your code should include the -webkit-border-radius vendor prefix that uses the $radius parameter.
- Your code should include the -moz-border-radius vendor prefix that uses the $radius parameter.
- Your code should include the -ms-border-radius vendor prefix that uses the $radius parameter.
- Your code should include the general border-radius rule that uses the $radius parameter.
- Your code should call the border-radius mixin using the @include keyword, setting it to 15px.
-->
<style type='text/scss'>
@mixin border-radius($radius) {
-webkit-border-radius: $radius;
-moz-border-radius: $radius;
-ms-border-radius: $radius;
border-radius: $radius;
}
#awesome {
width: 150px;
height: 150px;
background-color: green;
@include border-radius(15px);
}
</style>
<div id="awesome"></div>