5 CSS tricks you did not know
user profile avatar
Tech Wizard

Published on • 🕑6 min read

Five Must Know CSS Tricks to Save You Time

0likes1

Blog views466

Listen to this blog

HTML & CSS are the predominant languages for any newbie front-end developer to learn. CSS or Cascading Style Sheets is the language we use to style an HTML document. CSS describes how HTML elements should be displayed. However, CSS is not as easy as it looks, and mastering it takes time. Here are some 5 tricks that can help make you a css pro.

1. Styling Images

When it comes to web design, captivating visuals can make all the difference. Images play a crucial role in creating an engaging and memorable user experience.

Styling images properly could help reduce the loading time for images. Despite setting width, height, and alt properties, there are other advanced CSS features for images such as aspect ratio that help set the responsiveness. Here is how to properly style images according to Kevin Powell.

.img {
   max-width: 100%;
   height: auto;
   vertical-align:middle;
   font-style: italic;
   background-repeat:no-repeat;
   background-cover: cover;
   shape-margin:0.75rem;
}

Max-width and height auto-properties are important to help ensure the image is responsive and stop the image from overflowing. There is a difference when you set the width and max-width to 100%. using width: 100% allows the image to stretch or shrink to fit the container’s width, while max-width: 100% ensures the image does not exceed its original size but can still scale down to fit within the container.

Vertical-align is a replacement for a display block that helps preserve the line height but moves the image down vertically so it no longer seems like it has uneven spacing. The font-style italic is used to style the image description and thus differentiate the alt text from the rest of the text. If need be, you can also style this using the image[alt] selector.

You might be wondering why we need the background image for an image. Kevin explained that the background image background-cover: cover and background-repeat: no-repeat helps set a placeholder (low-resolution of the image) to serve as a skeleton loader when the user is on a slow network.

However, another solution for this would be to use webp images or convert your images to progressive jpeg using tools such as Optimizilla or Riot. This will help the images load faster and therefore no need for a skeleton loader.

Lastly, the shape margin is useful especially when floating an image. This gives so spacing to the image and in the current setup, it does not do anything unless you end up floating the image.

2. Scroll Based Animation

We have all seen those fancy websites where content is updated dynamically as you scroll. You might think that this requires a lot of JavaScript to achieve, while in the real sense, you can use CSS tricks to achieve similar effects.

One alternative to this is to use a popular library called animate-on-scroll but the library has not been touched in seven years and only has 49 downloads. Another alternative is to use animate-on-scroll-framer which also has 3 downloads.

Upon further research, I also found a CSS feature named scroll-timeline although it is also not supported anywhere. Looks like we have to do this ourselves using Intersection Observer API.

To use the intersection observer api, we need some javascript code that applies a class when the element is intersecting. We will add a class of hidden to all elements we want to animate on scroll and use the observer to add a class of show when the element is intersecting.

const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      entry.target.classList.add("show");
    } else {
      entry.target.classList.remove("show");
    }
  });
});
const hiddenElements = document.querySelectorAll(".hidden");
hiddenElements.forEach((element) => observer.observe(element));

We need to add a class of hidden to a section and then animate the section on scroll. It is important to ensure each section that you want to animate takes the full viewport height for better scroll behavior. 

.section-to-animate{
  min-height: 100dvh;
}
.hidden {
  opacity: 0;
  transition: all 1s ease-in-out; /* fade animation */
  filter: blur(0);
  transform: translateY(-100%);
}
.show {
  opacity: 1;
  filter: blur(1);
  transform: translateX(0);
  transition-delay: 0.2s;
}
@media (prefers-reduced-motion) {
  .hidden {
    transition: none; /* be polite */
  }
}

For more advanced cases that make you look fancy, look at this pen and do not forget to fork it.

3. CSS Variables

CSS Variables enhance efficiency by allowing you to declare variables with local or global scope, change the variables with JavaScript, and change the variables based on media queries. A good way to use these variables is when declaring colors.

We can declare global variables using the selector in CSS :root selector and adding the variable to use using the var function. We can create fallback variables and declare local variables that override the global variable on a component.

/* global */
:root {
  --primary-color: #3498db;
  --secondary-color: #2ecc71;
  --font-size: 16px;
  --padding: 10px;
  --color: white;
}
/* local */
.button {
  --color: whitesmoke;
}
body {
  background-color: var(--primary-color);
  color: var(--secondary-color);
  font-size: var(--font-size);
  padding: var(--padding);
}
.button {
  background-color: var(--primary-color);
  padding: calc(var(--padding) * 2); /* Using a calculation with the variable */
  font-size: var(--font-size);
}
/* using a fallback value */
body {
  background-color: var(--primary-color, skyblue);
}

This would also work great using media queries. The variables can be modified using a media query to ensure a responsive design. This could range from updating color in dark and light modes and changing font size in small devices. For more knowledge, check out this tutorial guide: CSS Variables - An Introduction to CSS Custom Properties

:root {
  --font-size: 16px;
}
@media (min-width: 768px) {
  :root {
      --font-size: 18px;
  }
}
@media (min-width: 1024px) {
  :root {
      --font-size: 20px;
  }
}
body {
  font-size: var(--font-size);
}

4. Responsive Font Size

Responsive design is one of the major requirements in modern web design. Making sure the text changes as device width changes often involves using a lot of media queries to change the font sizes. However, there are simpler solutions like using CSS viewport width and clamp() function which is currently supported in all browsers.

We use viewport units to size our text to ensure the typography is responsive to the device's width. Instead of setting custom font sizes for each device using media queries, we can ensure that our text is responsive and increases or decreases as device width changes. 

However, the viewport text can get very small on smaller devices or very large on larger devices, and thus the a need to combine this with clamp(). Another problem with viewport units is that you cannot zoom in or out, and thus accessibility features might not work.

The clamp() CSS function clamps a middle value within a range of values between a defined minimum bound and a maximum bound. The function takes three parameters: a minimum value, a preferred value, and a maximum allowed value.

:root {
  --min-font-size: 1.2px;
  --max-font-size: 8rem;
  --font-xl: clamp(3.5rem, 12vw+1rem, 8rem);
  --font-md: 2rem;
  --font-sm: 1.5rem;
}
h1 {
  font-size: clamp(var(--min-font-size), 6vw, var(--max-font-size));
}
p {
  font-size: clamp(var(--font-sm), 3vw, var(--font-md));
}

5. CSS Based Validations

If you have ever dealt with forms, then you understand the need to validate form inputs and show errors to users without JavaScript. Errors could include setting a red background color if the input is invalid, and a green when the input is valid. This should be done in combination with HTML patterns, maxLength, and types.

One major problem is that if we give a form input a required attribute and use CSS invalid property, the form will appear as invalid even when the user has not typed anything. Of course, this is a bad experience for the user. To fix this, new CSS features such as user-invalid and placeholdershown property.

/* the old way */
input:invalid {
  border: 1px solid red;
  background-color: #ff7f7f;
}
input:valid {
  border: 1px solid green;
  background-color: lightgreen;
}
/* show on user input */
input:user-invalid {
  border: 1px solid red;
  background-color: #ff7f7f;
}
input:user-valid {
  border: 1px solid green;
  background-color: lightgreen;
}
/* user-valid and user-invalid has low browser support */
input:not(:placeholder-shown):invalid {
  border: 1px solid red;
  background-color: #ff7f7f;
}
input:not(:placeholder-shown):valid {
  border: 1px solid green;
  background-color: lightgreen;
}
/* placeholder-shown has great browser support */

You can play around with this code in Codepen. Here are the results.

Conclusion

We have discussed some simple CSS tricks that could be lifesaving. These tricks could help you avoid overusing JavaScript for simple tasks that can be accomplished by just CSS. Follow me and sign up to be a Tech Tales member today to learn more and also share some tricks in the comments.

Like what you see? Share with a Friend

0 Comments

1 Likes

Comments (0)

sort comments

Before you comment please read our community guidelines


Please Login or Register to comment

conversation-starter

This thread is open to discussion

✨ Be the first to comment ✨