A simple SASS mixin to center divs using absolute positioning and 50% transform.
A Pen by Andrew Houle on CodePen.
A simple SASS mixin to center divs using absolute positioning and 50% transform.
A Pen by Andrew Houle on CodePen.
| <div class="foo"> | |
| <div class="bar"> | |
| <div class="content">Look ma, I'm centered!</div> | |
| </div> | |
| </div> |
| @mixin ctr($axis: "both"){ | |
| position:absolute; | |
| @if $axis == "y"{ | |
| top: 50%; | |
| transform: translateY(-50%); | |
| } | |
| @if $axis == "x"{ | |
| left: 50%; | |
| transform: translateX(-50%); | |
| } | |
| @if $axis == "both"{ | |
| top: 50%; | |
| left: 50%; | |
| transform: translate(-50%,-50%); | |
| } | |
| } | |
| .foo { | |
| position: absolute; | |
| height: 100%; | |
| width: 100%; | |
| background: red; | |
| } | |
| .bar { | |
| @include ctr(both); | |
| height: 100px; | |
| width: 50%; | |
| background: blue; | |
| } | |
| .content { | |
| @include ctr(both); | |
| color: #fff; | |
| font-family: helvetica, sans-serif; | |
| text-align: center; | |
| font-weight: bold; | |
| font-size: 18px; | |
| padding: 20px; | |
| width: 100%; | |
| box-sizing: border-box; | |
| } |