CSS resets help enforce style consistency across different browsers with a clean slate for styling elements. There are plenty of reset patterns to find, or you can use a more simplified reset approach:
You can specify all of an element’s properties using the all shorthand. Setting the value to unset changes an element’s properties to their initial values:
Sighted keyboard users rely on focus to determine where keyboard events go in the page. Make focus for form elements stand out and consistent than a browser’s default implementation:
The aspect-ratio property allows you to easily size elements and maintain consistent width-to-height ratio. This is incredibly useful in responsive web design to prevent layout shift. Use object-fit with it to prevent disrupting the layout if the height/width values of images changes.
Make list items look like a real, comma-separated list:
ul > li:not(:last-child)::after {
content: ",";
}
Use the :not() pseudo-class and no comma will be added to the last item.
[!NOTE]
This tip may not be ideal for accessibility, specifically screen readers. And copy/paste from the browser doesn’t work with CSS-generated content. Proceed with caution.
[!NOTE]
This tip may not be ideal for accessibility, specifically screen readers. And copy/paste from the browser doesn’t work with CSS-generated content. Proceed with caution.
The :is() pseudo-class is used to target multiple selectors at once, reducing redundancy and enhancing code readability. This is incredibly useful for writing large selectors in a more compact form.
Using 20% for padding makes the height of the box equal to 20% of its width. No matter the width of the viewport, the child div will keep its aspect ratio (100% / 20% = 5:1).
This is a great trick for a custom user stylesheet. Avoid overloading a user with sound from a video that autoplays when the page is loaded. If the sound isn’t muted, don’t show the video:
video[autoplay]:not([muted]) {
display: none;
}
Once again, we’re taking advantage of using the :not() pseudo-class.
The type font size in a responsive layout should be able to adjust with each viewport. You can calculate the font size based on the viewport height and width using :root:
:root {
font-size: calc(1vw + 1vh + 0.5vmin);
}
Now you can utilize the root em unit based on the value calculated by :root:
Set font-size on Form Elements for a Better Mobile Experience
To avoid mobile browsers (iOS Safari, et al.) from zooming in on HTML form elements when a <select> drop-down is tapped, add font-size to the selector rule:
Pointer events allow you to specify how the mouse interacts with the element it’s touching. To disable the default pointer event on a button, for instance:
If you have HTML elements that are empty, i.e., the content has yet to be set either by a CMS or dynamically injected (e.g., <p class="error-message"></p>) and it’s creating unwanted space on your layout, use the :empty pseudo-class to hide the element on the layout.
:empty {
display: none;
}
[!NOTE]
Keep in mind that elements with whitespace aren’t considered empty, e.g., <p class="error-message"> </p>.
margin-inline defines the inline start and end margins of an element. So instead of using margin-left and margin-right we can use the inline property to define both.
.div {
margin-inline: auto;
}
The same can be done for margin-block with defines the block start and end margins, i.e., margin-top and margin-bottom.
[!NOTE]
I’ve had less time available to maintain the growing list of translated tips; adding a new tip requires including it with over a dozen translations. For that reason, translated README files are likely to not include all the tips listed on the main README file.
CSS Protips
A collection of tips to help take your CSS skills pro.
Contents
Protips
box-sizingunsetInstead of Resetting All Properties:not()to Apply/Unapply Borders on Navigationline-heighttobody:focusfor Form Elementsaspect-ratioInstead of Height/Widthnth-childmax-heightfor Pure CSS Sliders:is()remfor Global Sizing; Useemfor Local Sizing:rootfor Flexible Typefont-sizeon Form Elements for a Better Mobile Experiencedisplay: noneon Line Breaks Used as Spacing:emptyto Hide Empty HTML Elementsmargin-inlineinstead ofmarginUse a CSS Reset
CSS resets help enforce style consistency across different browsers with a clean slate for styling elements. There are plenty of reset patterns to find, or you can use a more simplified reset approach:
Now elements will be stripped of margins and padding, and
box-sizinglets you manage layouts with the CSS box model.Demo
Back to top
Inherit
box-sizingLet
box-sizingbe inherited fromhtml:This makes it easier to change
box-sizingin plugins or other components that leverage other behavior.Demo
Back to top
Use
unsetInstead of Resetting All PropertiesWhen resetting an element’s properties, it’s not necessary to reset each individual property:
You can specify all of an element’s properties using the
allshorthand. Setting the value tounsetchanges an element’s properties to their initial values:Back to top
Use
:not()to Apply/Unapply Borders on NavigationInstead of putting on the border…
…and then taking it off the last element…
…use the
:not()pseudo-class to only apply to the elements you want:Here, the CSS selector is read as a human would describe it.
Demo
Back to top
Check if Font Is Installed Locally
You can check if a font is installed locally before fetching it remotely, which is a good performance tip, too.
H/T to Adam Argyle for sharing this protip and demo.
Back to top
Add
line-heighttobodyYou don’t need to add
line-heightto each<p>,<h*>, et al. separately. Instead, add it tobody:This way textual elements can inherit from
bodyeasily.Demo
Back to top
Set
:focusfor Form ElementsSighted keyboard users rely on focus to determine where keyboard events go in the page. Make focus for form elements stand out and consistent than a browser’s default implementation:
Demo
Back to top
Vertically-Center Anything
No, it’s not black magic, you really can center elements vertically. You can do this with flexbox…
…and also with CSS Grid:
Demo
Back to top
Use
aspect-ratioInstead of Height/WidthThe
aspect-ratioproperty allows you to easily size elements and maintain consistent width-to-height ratio. This is incredibly useful in responsive web design to prevent layout shift. Useobject-fitwith it to prevent disrupting the layout if the height/width values of images changes.Learn more about the
aspect-ratioproperty in this web.dev post.Demo
Back to top
Comma-Separated Lists
Make list items look like a real, comma-separated list:
Use the
:not()pseudo-class and no comma will be added to the last item.Back to top
Select Items Using Negative
nth-childUse negative
nth-childin CSS to select items 1 through n.Or, since you’ve already learned a little about using
:not(), try:Demo
Back to top
Use SVG for Icons
There’s no reason not to use SVG for icons:
SVG scales well for all resolution types and is supported in all browsers back to IE9. Ditch your .png, .jpg, or .gif-jif-whatev files.
Back to top
Use the “Lobotomized Owl” Selector
It may have a strange name but using the universal selector (
*) with the adjacent sibling selector (+) can provide a powerful CSS capability:In this example, all elements in the flow of the document that follow other elements will receive
margin-top: 1.5em.Demo
Back to top
Use
max-heightfor Pure CSS SlidersImplement CSS-only sliders using
max-heightwith overflow hidden:The element expands to the
max-heightvalue on hover and the slider displays as a result of the overflow.Back to top
Equal-Width Table Cells
Tables can be a pain to work with. Try using
table-layout: fixedto keep cells at equal width:Pain-free table layouts.
Demo
Back to top
Get Rid of Margin Hacks With Flexbox
When working with column gutters you can get rid of
nth-,first-, andlast-childhacks by using flexbox’sspace-betweenproperty:Now column gutters always appear evenly-spaced.
Back to top
Use Attribute Selectors with Empty Links
Display links when the
<a>element has no text value but thehrefattribute has a link:That’s really convenient.
Demo
Back to top
Control Specificity Better with
:is()The
:is()pseudo-class is used to target multiple selectors at once, reducing redundancy and enhancing code readability. This is incredibly useful for writing large selectors in a more compact form.The above ruleset is equivalent to the following number selector rules…
Demo
Back to top
Style “Default” Links
Add a style for “default” links:
Now links that are inserted via a CMS, which don’t usually have a
classattribute, will have a distinction without generically affecting the cascade.Back to top
Intrinsic Ratio Boxes
To create a box with an intrinsic ratio, all you need to do is apply top or bottom padding to a div:
Using 20% for padding makes the height of the box equal to 20% of its width. No matter the width of the viewport, the child div will keep its aspect ratio (100% / 20% = 5:1).
Demo
Back to top
Style Broken Images
Make broken images more aesthetically-pleasing with a little bit of CSS:
Now add pseudo-elements rules to display a user message and URL reference of the broken image:
Back to top
Use
remfor Global Sizing; Useemfor Local SizingAfter setting the base font size at the root (
html { font-size: 100%; }), set the font size for textual elements toem:Then set the font-size for modules to
rem:Now each module becomes compartmentalized and easier to style, more maintainable, and flexible.
Back to top
Hide Autoplay Videos That Aren’t Muted
This is a great trick for a custom user stylesheet. Avoid overloading a user with sound from a video that autoplays when the page is loaded. If the sound isn’t muted, don’t show the video:
Once again, we’re taking advantage of using the
:not()pseudo-class.Back to top
Use
:rootfor Flexible TypeThe type font size in a responsive layout should be able to adjust with each viewport. You can calculate the font size based on the viewport height and width using
:root:Now you can utilize the
root emunit based on the value calculated by:root:Demo
Back to top
Set
font-sizeon Form Elements for a Better Mobile ExperienceTo avoid mobile browsers (iOS Safari, et al.) from zooming in on HTML form elements when a
<select>drop-down is tapped, addfont-sizeto the selector rule:Back to top
Use Pointer Events to Control Mouse Events
Pointer events allow you to specify how the mouse interacts with the element it’s touching. To disable the default pointer event on a button, for instance:
It’s that simple.
Back to top
Set
display: noneon Line Breaks Used as SpacingAs Harry Roberts pointed out, this can help prevent CMS users from using extra line breaks for spacing:
Back to top
Use
:emptyto Hide Empty HTML ElementsIf you have HTML elements that are empty, i.e., the content has yet to be set either by a CMS or dynamically injected (e.g.,
<p class="error-message"></p>) and it’s creating unwanted space on your layout, use the:emptypseudo-class to hide the element on the layout.Back to top
Support
Current versions of Chrome, Firefox, Safari, and Edge.
Back to top
Use
margin-inlineinstead ofmarginmargin-inlinedefines the inline start and end margins of an element. So instead of usingmargin-leftandmargin-rightwe can use the inline property to define both.The same can be done for
margin-blockwith defines the block start and end margins, i.e.,margin-topandmargin-bottom.Demo
Back to top
Translations
Back to top