center block
view sourceGive a block element auto
left- and right-margins and (optionally) set its max-width
.
- use-name
-
scut-center-block
- type
- mixin, with a default-values placeholder
- arguments
-
-
$max-width
- default
-
false
-
You, being wise, probably know that setting margin-left: auto; margin-right: auto;
on a block element with a defined width will center that element. You probably do it all the time.
So why a utility?
- To make sure you're setting
margin-left
andmargin-right
when that's all you need to set — instead of also overridingmargin-top
andmargin-bottom
with a rule likemargin: 0 auto;
. - To organize and name the pattern, describing what is being done — you are centering a block — whereas
margin: auto;
does not explain itself. - To provide a little handy shortcut for the all-too-common pattern of setting
auto
left and right margins along with amax-width
. (max-width
instead ofwidth
, so the element shrinks with the viewport, if it comes to that — I find myself doing it that way most often.)
example
SCSS
.eg-center-block-1 {
width: 8em;
@include scut-center-block;
// or @extend %scut-center-block;
}
.eg-center-block-2 {
margin-top: 1em;
@include scut-center-block(80%);
}
compiled CSS
.eg-center-block-1 {
width: 8em;
margin-left: auto;
margin-right: auto;
}
.eg-center-block-2 {
margin-top: 1em;
margin-left: auto;
margin-right: auto;
max-width: 80%;
}
Result
Variation 1
Variation 2
A
max-width
value for the to-be-centered block.