Code Monkey home page Code Monkey logo

css-protips's Introduction

light bulb icon

CSS Protips Awesome

A collection of tips to help take your CSS skills pro.

For other great lists check out @sindresorhus's curated list of awesome lists.

Table of Contents

Protips

  1. Use a CSS Reset
  2. Inherit box-sizing
  3. Use unset Instead of Resetting All Properties
  4. Use :not() to Apply/Unapply Borders on Navigation
  5. Check if Font Is Installed Locally
  6. Add line-height to body
  7. Set :focus for Form Elements
  8. Vertically-Center Anything
  9. Use aspect-ratio Instead of Height/Width
  10. Comma-Separated Lists
  11. Select Items Using Negative nth-child
  12. Use SVG for Icons
  13. Use the "Lobotomized Owl" Selector
  14. Use max-height for Pure CSS Sliders
  15. Equal-Width Table Cells
  16. Get Rid of Margin Hacks With Flexbox
  17. Use Attribute Selectors with Empty Links
  18. Control Specificity Better With :is()
  19. Style "Default" Links
  20. Intrinsic Ratio Boxes
  21. Style Broken Images
  22. Use rem for Global Sizing; Use em for Local Sizing
  23. Hide Autoplay Videos That Aren't Muted
  24. Use :root for Flexible Type
  25. Set font-size on Form Elements for a Better Mobile Experience
  26. Use Pointer Events to Control Mouse Events
  27. Set display: none on Line Breaks Used as Spacing
  28. Use :empty to Hide Empty HTML Elements

Use 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:

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

Now elements will be stripped of margins and padding, and box-sizing lets you manage layouts with the CSS box model.

Tip

If you follow the Inherit box-sizing tip below you might opt to not include the box-sizing property in your CSS reset.

back to table of contents

Inherit box-sizing

Let box-sizing be inherited from html:

html {
  box-sizing: border-box;
}

*,
*::before,
*::after {
  box-sizing: inherit;
}

This makes it easier to change box-sizing in plugins or other components that leverage other behavior.

back to table of contents

Use unset Instead of Resetting All Properties

When resetting an element's properties, it's not necessary to reset each individual property:

button {
  background: none;
  border: none;
  color: inherit;
  font: inherit;
  outline: none;
  padding: 0;
}

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:

button {
  all: unset;
}

back to table of contents

Use :not() to Apply/Unapply Borders on Navigation

Instead of putting on the border...

/* add border */
.nav li {
  border-right: 1px solid #666;
}

...and then taking it off the last element...

/* remove border */
.nav li:last-child {
  border-right: none;
}

...use the :not() pseudo-class to only apply to the elements you want:

.nav li:not(:last-child) {
  border-right: 1px solid #666;
}

Here, the CSS selector is read as a human would describe it.

back to table of contents

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.

@font-face {
  font-family: "Dank Mono";
  src:
    /* Full name */
    local("Dank Mono"),
    /* Postscript name */
    local("Dank Mono"),
    /* Otherwise, download it! */
    url("//...a.server/fonts/DankMono.woff");
}

code {
  font-family: "Dank Mono", system-ui-monospace;
}

H/T to Adam Argyle for sharing this protip and demo.

back to table of contents

Add line-height to body

You don't need to add line-height to each <p>, <h*>, et al. separately. Instead, add it to body:

body {
  line-height: 1.5;
}

This way textual elements can inherit from body easily.

back to table of contents

Set :focus for Form Elements

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:

a:focus,
button:focus,
input:focus,
select:focus,
textarea:focus {
  box-shadow: none;
  outline: #000 dotted 2px;
  outline-offset: .05em;
}

back to table of contents

Vertically-Center Anything

No, it's not black magic, you really can center elements vertically. You can do this with flexbox...

html,
body {
  height: 100%;
}

body {
  align-items: center;
  display: flex;
  justify-content: center;
}

...and also with CSS Grid:

body {
  display: grid;
  height: 100vh;
  place-items: center;
}

Tip

Want to center something else? Vertically, horizontally...anything, anytime, anywhere? CSS-Tricks has a nice write-up on doing all of that.

back to table of contents

Use aspect-ratio Instead of Height/Width

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.

img {
  aspect-ratio: 16 / 9; /* width / height */
  object-fit: cover;
}

Learn more about the aspect-ratio property in this web.dev post.

back to table of contents

Comma-Separated Lists

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.

back to table of contents

Select Items Using Negative nth-child

Use negative nth-child in CSS to select items 1 through n.

li {
  display: none;
}

/* select items 1 through 3 and display them */
li:nth-child(-n+3) {
  display: block;
}

Or, since you've already learned a little about using :not(), try:

/* select all items except the first 3 and display them */
li:not(:nth-child(-n+3)) {
  display: block;
}

back to table of contents

Use SVG for Icons

There's no reason not to use SVG for icons:

.logo {
  background: url("logo.svg");
}

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.

Note

If you have SVG icon-only buttons for sighted users and the SVG fails to load, this will help maintain accessibility:

.no-svg .icon-only::after {
  content: attr(aria-label);
}

back to table of contents

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:

* + * {
  margin-top: 1.5em;
}

In this example, all elements in the flow of the document that follow other elements will receive margin-top: 1.5em.

Tip

For more on the "lobotomized owl" selector, read Heydon Pickering's post on A List Apart.

back to table of contents

Use max-height for Pure CSS Sliders

Implement CSS-only sliders using max-height with overflow hidden:

.slider {
  max-height: 200px;
  overflow-y: hidden;
  width: 300px;
}

.slider:hover {
  max-height: 600px;
  overflow-y: scroll;
}

The element expands to the max-height value on hover and the slider displays as a result of the overflow.

back to table of contents

Equal-Width Table Cells

Tables can be a pain to work with. Try using table-layout: fixed to keep cells at equal width:

.calendar {
  table-layout: fixed;
}

Pain-free table layouts.

back to table of contents

Get Rid of Margin Hacks With Flexbox

When working with column gutters you can get rid of nth-, first-, and last-child hacks by using flexbox's space-between property:

.list {
  display: flex;
  justify-content: space-between;
}

.list .person {
  flex-basis: 23%;
}

Now column gutters always appear evenly-spaced.

back to table of contents

Use Attribute Selectors with Empty Links

Display links when the <a> element has no text value but the href attribute has a link:

a[href^="http"]:empty::before {
  content: attr(href);
}

That's really convenient.

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.

back to table of contents

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.

:is(section, article, aside, nav) :is(h1, h2, h3, h4, h5, h6) {
  color: green;
}

The above ruleset is equivalent to the following number selector rules...

section h1, section h2, section h3, section h4, section h5, section h6,
article h1, article h2, article h3, article h4, article h5, article h6,
aside h1, aside h2, aside h3, aside h4, aside h5, aside h6,
nav h1, nav h2, nav h3, nav h4, nav h5, nav h6 {
  color: green;
}

back to table of contents

Style "Default" Links

Add a style for "default" links:

a[href]:not([class]) {
  color: #008000;
  text-decoration: underline;
}

Now links that are inserted via a CMS, which don't usually have a class attribute, will have a distinction without generically affecting the cascade.

back to table of contents

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:

.container {
  height: 0;
  padding-bottom: 20%;
  position: relative;
}

.container div {
  border: 2px dashed #ddd;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0;
  width: 100%;
}

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).

back to table of contents

Style Broken Images

Make broken images more aesthetically-pleasing with a little bit of CSS:

img {
  display: block;
  font-family: sans-serif;
  font-weight: 300;
  height: auto;
  line-height: 2;
  position: relative;
  text-align: center;
  width: 100%;
}

Now add pseudo-elements rules to display a user message and URL reference of the broken image:

img::before {
  content: "We're sorry, the image below is broken :(";
  display: block;
  margin-bottom: 10px;
}

img::after {
  content: "(url: " attr(src) ")";
  display: block;
  font-size: 12px;
}

Tip

Learn more about styling for this pattern in Ire Aderinokun's post.

back to table of contents

Use rem for Global Sizing; Use em for Local Sizing

After setting the base font size at the root (html { font-size: 100%; }), set the font size for textual elements to em:

h2 {
  font-size: 2em;
}

p {
  font-size: 1em;
}

Then set the font-size for modules to rem:

article {
  font-size: 1.25rem;
}

aside .module {
  font-size: .9rem;
}

Now each module becomes compartmentalized and easier to style, more maintainable, and flexible.

back to table of contents

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:

video[autoplay]:not([muted]) {
  display: none;
}

Once again, we're taking advantage of using the :not() pseudo-class.

back to table of contents

Use :root for Flexible Type

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 + .5vmin);
}

Now you can utilize the root em unit based on the value calculated by :root:

body {
  font: 1rem/1.6 sans-serif;
}

back to table of contents

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:

input[type="text"],
input[type="number"],
select,
textarea {
  font-size: 16px;
}

back to table of contents

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:

button:disabled {
  opacity: .5;
  pointer-events: none;
}

It's that simple.

back to table of contents

Set display: none on Line Breaks Used as Spacing

As Harry Roberts pointed out, this can help prevent CMS users from using extra line breaks for spacing:

br + br {
  display: none;
}

back to table of contents

Use :empty to Hide Empty HTML Elements

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>.

back to table of contents

Support

Current versions of Chrome, Firefox, Safari, and Edge.

back to table of contents

Translations

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.

back to table of contents

css-protips's People

Contributors

allthingssmitty avatar bityog avatar doggy8088 avatar duca7 avatar evertonfraga avatar fremdev avatar ivanwitzke avatar jiasm avatar jim63 avatar karna12 avatar manfromanotherland avatar manolasn avatar minthings avatar mitogh avatar monzter50 avatar nandamonroe avatar nunofca avatar pastparty avatar shfshanyue avatar songhn233 avatar taiwobello avatar tb619tev avatar tipoqueno avatar twogrey avatar unruly-mac avatar vanshikaa00 avatar vcoppolecchia avatar vladimircreator avatar xunziheng avatar zcdev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

css-protips's Issues

'Style "Default" Links' is not a pro tip

You suggest to use a[href]:not([class]) for a-Tags without an href-attribute. But why?
a is everything you need to style for this case. Heck, you can use a:link, a:visited if that floats your boat but adding two different type of selectors ([attribute], :not()) is in no way a pro tip.

Alternative for Apply/Unapply Borders

I personally use this technique in professional projects

.nav li + li {
  border-right: 1px solid #666;
}

this technique has less specificity and support IE7. Thought?

Translations

Sorry i tried commenting in the Translations section and i ended up makeing a new issue and i dont know how to delete it 😄

Good practices about :root

I see some projects using :root but I not have any idea about good practices about it. Have any tip for us?

Animation to any element

Hi,

Please can I add an animation on load, which can be added to any element via. a class.

@Keyframes slideInFromLeft {
0% {
transform: translateX(-100%);
}
100% {
transform: translateX(0);
}
}

.animation-element-onload {
animation: 1s ease-out 0s 1 slideInFromLeft;
}

Thank you,
Gemma

about flex layout

Using flex to do layout is pretty cool, but as the content goes more, there may be something wrong, for example, if I paste the h1 tag in your demo for 10 times, the document will only show it 9 times though there is a scroll bar, and if i decrease the browser's height, there will be more to lose, how could i solve this problem gracefully?

German translation formatting

@Unruly-MAC I was looking over the merged file for the German translation and there are some formatting issues. It looks like the table of contents hasn't been formatted correctly, and links and code snippets aren't in the proper format either. Can you look into that?

box-sizing inheritance questions

Is there a reason the html rule comes before the ***, :before, :after rule instead of after it?

Also, I thought that it was considered bad practice to use the universal selector?

2 points contradict each other

Use the "Lobotomized Owl" Selector and Consistent Vertical Rhythm are basically the same protip.

By applying the LobOwl selector you get a consistent vertical rhythm and the benefit of no left over margins at the top or bottom of the containing element.

With the example presented for Consistent Vertical Rhythm, some margin will be leftover on the last element (unless using the :not trick of course).

I suggest the Consistent Vertical Rhythm tip be removed and a little more explanation added to the LobOwl tip.

Add Attribute Selectors

You can use attribute selectors to display the link when the a-tag is empty but the href-tag is an link.

Example:
html:

<a href="http://google.de"></a>
<a href=""></a>
<a href="http://bing.com">Test 1</a>
<a href="#">Test2</a>

css:

a[href^=http]:empty::before {
    content: attr(href);
}

Some misunderstandings about adjacent sibling combinator (+) as alternative way of using :not() pseudo-class

There is some alternative approach In the section about :not() CSS pseudo-class :
Use :not() to Apply/Unapply Borders on Navigation

Sure, you can use .nav li + li, but with :not() the intent is very clear and the CSS selector defines the border the way a human would describe it.

I think this adjacent sibling combinator has a different meaning(inner logic) rather than :not() CSS pseudo-class. Of course in the context of the Borders on Navigation.
What I mean?

If we apply adjacent sibling combinator:

.nav li + li {
  border-right: 1px solid #666;
}

We will have border-right on the li elements except the first one. example pen

But with :not() pseudo-class we will have right behaviour:

.nav li:not(:last-child) {
  border-right: 1px solid #666;
}

Question: Can we replace pseudo-class with adjacent sibling combinator? Or there's some error here? Or I didn't catch intent of this CSS tip?

Please don't recommend disabling subpixel anti-aliasing everywhere

html {
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;

OS X has an option to disable "LCD font smoothing" in System Preferences, so those who don't like it can do so. But it doesn't have an option to force sharp text rendering on pages that chose to make it blurry.

Please don't recommend setting these properties on html. They do help to make icon fonts less wonky and for some fonts rendered in white-on-black, but in disabling it everywhere for everyone is IMHO too drastic.

polish translation

Hello Mate,

I have noticed you have a wide variety of languages. I am going to add Polish into it and send you the results.

Thank you
Justin Oliver

Issues with `line-height`

line-height to body

body {
  line-height: 1;
}

The above value is too small and will create problems with descenders/ascenders. I think it'd be better to use a more realistic one (i.e. 1.5) so people who copy/paste won't find out the hard way.

Use :root for Flexible Type

It is better to use unit-less values with line-height because the way inheritance works with this property (what is inherited is a computed value).

So I'd suggest to use:

body {
  font: 1em/1.6rem sans-serif;
}

negative margins

using negative margins to get rid of :first-child and :last-child selector

instead of this

.navigation li {
  display: inline-block;
  margin: 0 .5rem;
}

.navigation li:first-child {
  margin-left: 0;
}

.navigation li:last-child {
  margin-right: 0;
}

you could write

.navigation {
  margin: 0 -.5rem;
}

.navigation li {
  display: inline-block;
  margin: 0 .5rem;
}

It is similar to the flexbox space-betweet technique but flexbox does not work in every situation.

If you agree with me, I could send you a PR :)

* + * Incorrect verb: Precede.

Wouldn't this mean that "anything" that's after anything gets a margin on top? The opposite of precede — original reference document uses "proceed."

Suggested edit.

In this example, all elements in the flow of the document that follow other elements will receive margin-top: 1.5em.

TOC needed

At some point a table of contents will likely be needed to make it easier to parse through tips.

Not a fan of the first :not tip

I don't think the :not tip should be advised. You're adding 1 more level specificity to all of nav items except the last one as opposed to that 1 level to just the last one. Makes it a bit more annoying to overwrite when it comes to it.

Pure CSS Slider demo

One can't reproduce the subj because of lack of styles. Can You post codepen example, please?

Aligns the flexible container's items

Align the flex items at the centre of the container.

div { display: flex; justify-content: center; }
This is the quick and easy way to get your divs aligned.

Add tip: wrapper utility

You should add a tip for a simple wrapper/container utility. For example:

.wrapper {
  margin-right: auto;
  margin-left:  auto;
  max-width: 960px;
  padding-right: 10px;
  padding-left:  10px;
}

It's explained more in this css-tricks article.

I'd be happy to add it if you want.

Suggesting another use of :not()

Not an issue, just a suggestion.
Since you're already using :not() on two of those pro tips, I'd suggest to use it on another one:

The Select Items Using Negative nth-child:

li {
    display: none;
}

/* select items 1 through 3 and display them */
li:nth-child(-n+3) {
    display: block;
}

Could be just:

/* select items 1 through 3 and display them */
li:not(:nth-child(-n+3)) {
    display: none;
}

Thanks for sharing those!

Translations

I'm setting up this card as a way to track PR's for language translations. If you're translating this repo please add a comment indicating which language so we're not duplicating work. 😎

Your PR should include the following:

  1. Add a language/country code folder to the translations folder, e.g., translations/fr-FR
  2. Add a README.md file with the translation to the language/country code folder, e.g., .../fr-FR/README.md

You can find more information about contributing under the Language Translations section of the Contribution Guidelines.

I'm not looking for pasting into Google Translate; I can do that myself and it's not accurate. 💁🏼 I appreciate your help with this. 👍🏼


Translations (and any others that may not be on this list):

  • Chinese - simplified (zh-CN)
  • Chinese - traditional (zh-TW)
  • French (fr-FR)
  • German (de-DE)
  • Greek (gr-GR)
  • Gujarati (gu-GU)
  • Italian (it-IT)
  • Japanese (ja-JP)
  • Korean (ko-KR)
  • Polish (pl-PL)
  • Portuguese - Brazilian (pt-BR)
  • Portuguese - European (pt-PT)
  • Russian (ru-RU)
  • Spanish (es-ES)
  • Vietnamese (vn-VN)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.