<div class="container">
<h1>
Convert <em>px</em> to <em>rem</em> using Sass
</h1>
<div class="box box--type-01">
<p>
<strong> <em>Px</em> to <em>rem</em> - Method 1</strong> <br>
- using a <code>@mixing</code> with predefined property
</p>
<pre>@mixin width($value) {
width: ($value / 16) + rem;
}
@mixin height($value) {
height: ($value / 16) + rem;
}
.box {
@include width(400);
@include height(400);
}</pre>
</div>
<div class="box box--type-02">
<p>
<strong> <em>Px</em> to <em>rem</em> - Method 2</strong> <br>
- using a <code>@mixing</code> with 2 arguments
</p>
<pre>@mixin toRem($property, $value) {
#{$property}: ($value / 16) + rem;
}
.box {
@include toRem(width, 400);
@include toRem(height, 400);
}</pre>
</div>
<div class="box box--type-03">
<p>
<strong> <em>Px</em> to <em>rem</em> - Method 3</strong> <br>
- using a <code>@function</code>
</p>
<pre>@function toRem($value) {
$remValue: ($value / 16) + rem;
@return $remValue;
}
.box {
width: toRem(400);
height: toRem(400);
}</pre>
</div>
</div>
// width in pixels
$widthInPx: 400;
//
// method 1 - using a mixing with predefined property
//
@mixin width($value) {
width: ($value / 16) + rem;
}
@mixin height($value) {
height: ($value / 16) + rem;
}
.box--type-01 {
@include width($widthInPx);
@include height($widthInPx);
background: #FDDFBD;
}
//
// method 2 - using a mixing with 2 arguments
//
@mixin toRem($property, $value) {
#{$property}: ($value / 16) + rem;
}
.box--type-02 {
@include toRem(width, $widthInPx);
@include toRem(height, $widthInPx);
background: #B7A99A;
}
//
// method 3 - using a function
//
@function toRem($value) {
$remValue: ($value / 16) + rem;
@return $remValue;
}
.box--type-03 {
width: toRem($widthInPx);
height: toRem($widthInPx);
background: #A1D2BD;
}
// pen styles
code {
color: #601C0E;
}
pre {
font-size: toRem(14);
color: #000716;
}
h1 {
color: #F4F1F2;
font-size: toRem(38);
width: 100%;
text-align: center;
margin-bottom: toRem(80);
}
p {
color: #000716;
font-size: toRem(16);
margin-bottom: toRem(30);
strong {
font-size: toRem(20);
}
}
.box {
color: #000716;
display: flex;
flex-direction: column;
padding: toRem(30);
margin-bottom: toRem(40);
&:last-child {
margin-bottom: 0;
}
@media(min-width: 1280px) {
margin-bottom: 0;
}
}
.container {
display: flex;
justify-content: space-around;
align-items: center;
align-content: center;
max-width: 1600px;
flex-direction: column;
padding-top: toRem(80);
padding-bottom: toRem(80);
@media(min-width: 1280px) {
flex-wrap: wrap;
flex-direction: row;
height: 100vh;
}
}
body {
background: #000716;
}
View Compiled