Share 15 useful CSS tips that you may not know yet, and suggest that every front-end developer should know about it...

5c7c680ec7baccddf60193b4a0e0f568.jpeg

opening

To get the most out of this article, I recommend that you open a CodePen or CodeSandbox tab so you can debug the code as you read the article.

CSS (Cascading Style Sheets) is a powerful markup language that allows web developers to create visually stunning and responsive designs. In my personal opinion, CSS (especially combined with JS for responsiveness) is probably the most important part of web development. Once we hit a certain performance threshold, the average user is more interested in your site's aesthetics than relative load time comparisons. With component libraries such as Bootstrap, Material, etc., it becomes very easy to abstract CSS out of the workflow. Some developers may choose to use a JavaScript-based approach to style management (i.e. adding/removing classes dynamically), but this results in more complex code and potentially slower applications. Today, we're going to explore some lesser-known CSS properties so you can add detail to your app without sacrificing performance, taking your front-end skills to the next level.

While there are many well-known CSS properties and techniques, there are also some lesser-known but extremely useful tricks that can take your web design to the next level. In this article, we'll explore 10 lesser-known CSS tricks to help you elevate your web design.

1. Use the :not() pseudo-class to simplify your CSS

The :not() pseudo-class allows you to apply styles to all elements that do not match the specified selector. This is a great way to simplify your CSS and avoid manually listing elements or applying classes to exclude certain elements.

Using the :not() pseudo-class can help you simplify your CSS code and avoid manually listing elements to exclude or adding extra classes. By using :not(), you can directly select the elements that need to be styled, without specifying styles for the elements to be excluded. This improves code maintainability and flexibility.

Hope this explanation helps you! If you have additional questions, please feel free to ask.

/* Apply styles to all elements except paragraph and anchor tags */
:not(p, a) {
  /* Your styles here */
}

2. Use the ::before pseudo-element to style the damaged image

Broken images can negatively affect the aesthetics of your site. To handle them gracefully, you can use the ::before pseudo-element and the content attribute to display an alternative message or icon in place of the broken image.

By using the ::before pseudo-element and the content attribute, you can insert custom content or icons in place of broken images to alert users that the image cannot be loaded or displayed. This improves the user experience and makes the page look more complete and professional.

By using the ::before pseudo-element and the content attribute, you can insert custom content or icons in place of broken images to alert users that the image cannot be loaded or displayed. This improves the user experience and makes the page look more complete and professional.

img::before {
  content: "Image not available";
  display: block;
  text-align: center;
  /* Additional styles here */
}

3. Use the :empty pseudo-class to hide empty elements

Sometimes, you may wish to hide empty elements in order to maintain a clean layout. You can use the :empty pseudo-class to hide these elements without using JavaScript.

By using the :empty pseudo-class, you can select and hide empty elements that have no children or text content. This is very useful for creating neat layouts, especially when your web content is dynamically generated. By hiding empty elements, you can improve the appearance of the page and ensure that only elements with content are displayed, improving the user experience.

div:empty {
  display: none;
}

4. Use calc() for dynamic calculation

The calc() function allows you to perform calculations in CSS in different units, such as percentages, pixels, and ems. This is especially useful when creating responsive designs.

By using the calc() function, you can perform dynamic calculations in CSS, adding, subtracting, multiplying or dividing values ​​in different units. This is great for creating responsive designs, as you can automatically adjust styles for different viewport sizes or element sizes. For example, you can use the calc() function to set the width of an element to 50% of the viewport width minus 20 pixels to achieve an adaptive layout.

Using the calc() function can make your CSS more flexible and maintainable, and at the same time help you easily achieve dynamic calculation effects.

.container {
  width: calc(100% - 20px);
}

5. Use the :hover pseudo-class and the transition property to animate elements

You can create simple animation effects by using the :hover pseudo-class and the transition property. It's a lightweight way to add interactivity to your designs without relying on JavaScript or external libraries.

Using the :hover pseudo-class in combination with the transition attribute, you can trigger style changes when the mouse hovers over an element and add smooth transitions to those changes. By adjusting the value of the transition property, you can control the transition speed, timing, and effect type to create a variety of animation effects.

Using the :hover pseudo-class and the transition attribute is a lightweight way to add some simple interactive effects to your design and enhance the user experience without relying on complex JavaScript code or external libraries.

.button {
  transition: background-color 0.3s ease-in-out;
}

.button:hover {
  background-color: #f00;
}

6. Use the * selector to apply global styles

The * selector is a wildcard selector that selects all elements on the page. By using this selector, you can easily apply global styles to your website.

Using the * selector is a convenient way to apply styles to all elements on a web page without having to specify selectors for each element individually. This is useful for setting global styles, such as setting default fonts, colors, or line heights, etc.

Note that the selector matches every element on the page, including nested elements. Therefore, when using selectors, you need to be careful to ensure that styles don't inadvertently affect elements that you don't want to change.

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

7. Styling the first and last child elements

You can use the :first-child and :last-child pseudo-classes to select and style the first and last child elements of a parent element. This is especially useful when styling lists or navigation menus.

Using the :first-child and :last-child pseudo-classes, you can directly select and style the first and last child elements of a parent element without adding additional classes or selectors for them. This is handy for adding specific styles to the first and last item of a list, or adding special effects to the first and last link of a navigation menu.

Using the :first-child and :last-child pseudo-classes can help you control the styling of elements more precisely without adding extra markup to your HTML.

li:first-child {
  font-weight: bold;
}

li:last-child {
  border: none;
}

8. Use the currentColor keyword for consistent color styling

By applying currentColor to the value of an attribute, you can make the value of the attribute consistent with the text color of the current element. This is very useful for achieving consistent color styling, especially when it comes to inheritance relationships between parent and child elements.

For example, you can apply currentColor to properties such as border color, background color, or shadow color to ensure they match the current element's text color. This simplifies styling, reduces maintenance, and ensures a consistent look.

Note that the currentColor keyword can only be used on properties that accept a color value, not all properties.

.button {
  color: #f00;
  border: 1px solid currentColor;
}

9. Use the :focus-within pseudo-class to style elements with focused child elements

The :focus-within pseudo-class helps you style elements that have focused children. When a child element gets focus, the parent element will be matched and the corresponding styles applied. This is useful for creating interactive forms or other situations where styling needs to be adjusted based on the focus state of a child element.

By using the :focus-within pseudo-class, you can easily style specific parent elements containing focused child elements to improve user experience and enhance interactivity.

It should be noted that the :focus-within pseudo-class may not be supported in some older versions of browsers, please make sure your target browser supports this pseudo-class.

.form-group:focus-within {
  border: 1px solid #f00;
}

10. Use CSS variables to easily switch themes

CSS variables, also known as custom properties, allow you to store and reuse values ​​throughout your stylesheets. This is especially helpful when creating themes or when multiple values ​​need to be changed at the same time.

By using CSS variables, you can define and use variables throughout your stylesheet, and after storing values ​​as variables, you can reuse those values ​​wherever you need them. This is especially useful when creating themes, as you can store theme-related values ​​for colors, fonts, spacing, etc. as variables, and then easily switch themes by changing the values ​​of the variables.

Another advantage of CSS variables is that when you need to change multiple values ​​at the same time, you only need to change the value of the variable instead of changing specific styles one by one. This provides a more convenient and flexible way of style management.

It should be noted that CSS variables may not be fully supported in some old browsers, please make sure your target browser supports CSS variables.

:root {
  --primary-color: #f00;
}

.button {
  background-color: var(--primary-color);
}

11. Use the :checked pseudo-class to set the input style for checkboxes and radio buttons

Customizing the appearance of checkbox and radio box inputs can be somewhat challenging due to inconsistencies between browsers. The :checked pseudo-class allows you to style these elements when they are checked, providing a consistent and visually pleasing user experience.

By using the :checked pseudo-class, you can style checkbox and radio button inputs when they are checked. This allows you to customize their appearance to match the overall design and provide better user feedback. You can change its background color, border style, icon, etc. to highlight the selected state.

It should be noted that different browsers may have different support and style settings for the :checked pseudo-class. Therefore, in order to obtain better compatibility, please conduct sufficient testing and make necessary style adjustments for different browsers.

By using the :checked pseudo-class, you can provide a consistent and pleasing appearance and user experience for checkbox and radio input.

input[type="checkbox"]:checked + label {
  background-color: #f00;
  /* Additional styles here */
}

input[type="radio"]:checked + label {
  border: 2px solid #f00;
  /* Additional styles here */
}

12. Use the :target pseudo-class to create scrolling effects without JavaScript

By using the :target pseudo-class, you can style elements when they are targeted by the current URL fragment identifier (the part after the "#"). This can be used to create scrolling effects or highlight specific sections without relying on JavaScript.

Using the :target pseudo-class, you can select and style specific elements based on URL fragment identifiers. When the user clicks on a link that contains a fragment identifier, the browser will automatically scroll to the corresponding element and apply the styles defined by the :target pseudo-class. This allows you to create the effect of scrolling to a specific section on the page, or to highlight positioned elements.

By using the :target pseudo-class, you can achieve some basic scrolling effects without relying on JavaScript code. This makes pages more lightweight and maintainable, and provides a way to implement scrolling effects in environments where JavaScript is not supported or disabled.

Note that the :target pseudo-class may not be fully supported in some older browsers, please make sure your target browser supports this pseudo-class.

section:target {
  background-color: #f0f;
  /* Additional styles here */
}

13. Use the ::selection pseudo-element to customize the text selection style

By using the ::selection pseudo-element, you can customize the appearance of selected text within an element. This can be used to create a more unified design by matching the text selection color with your website color scheme.

Using the ::selection pseudo-element, you can set styles for the selected text, including text color, background color, border, etc. By customizing text selection styles, you can improve the overall look and feel of your site and ensure that selected text matches your site's color scheme.

Note that different browsers may have different support and styling for the ::selection pseudo-element. Some browsers may only support text color and background color settings, while other style settings may have no effect. Therefore, when using the ::selection pseudo-element, please conduct sufficient testing and make necessary style adjustments as needed.

By using the ::selection pseudo-element, you can customize the appearance of selected text, adding personalization and consistency to your website.

::selection {
  background-color: #f00;
  color: #fff;
}

14. Use the :required and :optional pseudo-classes to style form inputs

Use the :required and :optional pseudo-classes to style a form input field based on whether it is marked as required or optional. This is very helpful for providing visual cues to users about the importance of a particular form field.

By using the :required and :optional pseudo-classes, you can style your form input fields according to their required state. For example, you can change the border color of an input field or the style of a label to highlight required fields or distinguish optional fields. Such styling helps communicate to users the importance and requirements of form fields.

By utilizing the :required and :optional pseudo-classes, you can provide visual cues for form input fields to help users better understand and fill out forms, and improve user experience.

Note that the :required and :optional pseudo-classes may not be fully supported in some older browsers, please make sure your target browser supports these pseudo-classes.

input:required {
  border: 2px solid #f00;
}

input:optional {
  border: 1px solid #ccc;
}

15. Use the ::placeholder pseudo-element to style the placeholder text of the input box

By using the ::placeholder pseudo-element, you can style the placeholder text inside the input field. This can be used to create visually consistent and attractive forms while providing helpful guidance to users.

Using the ::placeholder pseudo-element, you can set the style for the placeholder text of the input box, including text color, font style, alignment, etc. By customizing the style of the placeholder text, you can make the form more attractive and provide helpful guidance to help users understand the expected input of the input box.

Note that different browsers may have different support and styling for the ::placeholder pseudo-element. Some browsers may only support some style settings, while others may be ignored. Therefore, when using the ::placeholder pseudo-element, please conduct sufficient testing and make necessary style adjustments as needed.

By using the ::placeholder pseudo-element, you can set a personalized style for the placeholder text of the input box, improving the appearance and user experience of the form.

input::placeholder {
  color: #f00;
  font-style: italic;
}

Finish

Oops, that's really too much. Considering that there are over 500 unique properties, you can see why many developers prefer the versatility of JavaScript and shy away from CSS. However, as with anything related to code, perfection comes only with practice! Test out some of these properties in your favorite development environment like CodePen or CodeSandbox, and increase your familiarity with these lesser-known properties so you can incorporate them in your next project. If you have some favorite CSS tips or tricks, please share them in the comments - I'm still learning myself!

Due to the limited space of the article, today’s content will be shared here. At the end of the article, I would like to remind you that the creation of articles is not easy. If you like my sharing, please don’t forget to like and forward it, so that more people in need See. At the same time, if you want to gain more knowledge of front-end technology, welcome to follow me, your support will be the biggest motivation for me to share. I will continue to output more content, so stay tuned.

Guess you like

Origin blog.csdn.net/Ed7zgeE9X/article/details/131447888