
Change the aspect ratio of an image using CSS
24/09/2021In this post I'll show you how to change the aspect ratio of an image or element using CSS, and explain why this is important.
We can use conditional statements in Sass in the form of @if, @else, @else if and @if not. Much like other programming languages this will write a CSS statement only if the condition is met. They are really useful statements to use in loops and mixins where we are likely to want to check whether a condition evaluates to true or false.
We open our conditional with @if and can follow it with @else if or @else. When a condition gets met then the css gets generated:
@if $something {
// do something
} @else if $something-else {
// do something else
} @else {
// or do this
}
In Sass ‘null’ and ‘false’ are false; everything else is true
In my last post we looked at loops in Sass, so lets use the theme loop in our example.
$themeColours: (
"pink": #DC51AC,
"red": #D64651,
"orange": #E55937,
);
@each $themeColour, $i in $themeColours {
body {
&.#{$themeColour} {
background-color: $i;
@if $themeColour == "pink" {
color: #000;
} @else if $themeColour == "red" {
color: #fff;
} @else {
color: #DEEDEE;
}
}
}
}
Here we are looping through an array of theme colours to change the body text colour. We are using an if statement to check the key ($themeColour) for the values “pink” and “red” and otherwise setting a default colour. The output looks like this:
/* Output */
body.pink {
background-color: #DC51AC;
color: #000;
}
body.red {
background-color: #D64651;
color: #fff;
}
body.orange {
background-color: #E55937;
color: #DEEDEE;
}
You can also evaluate for false by using @if not. For @if not to work you have to put parenthesis around the argument:
$width: 50px;
div {
width: $width;
@if not ($width == 100px) {
background: red;
} else {
background: blue;
}
}
This statement sets the background to ‘red’ if $width is not equal to 100px and to ‘blue’ if $width is equal to 100px.
/* Output */
div {
width: 99px;
background: red;
}
In this post I'll show you how to change the aspect ratio of an image or element using CSS, and explain why this is important.
Here is how you can fix node incompatibility error, using "Node Sass does not yet support your current environment" as an example.
Need to make a directory in PHP? No Problem! mkdir has you covered... Need to recursively make directories in PHP? mkdir has you covered, too!
Learn how to regenerate and update WordPress media and image sizes both programmatically (without plugin), and also with a handy plugin.
Ever seen constants like __DIR__ and __FILE__ being used in PHP? These are 'Magic Constants', and this is how we can use them.
Learn how to use event listeners to detect and handle single and multiple keypress events in JavaScript. Add modifier keys to your application!