andrantis / css-protips

A collection of useful CSS protips

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

CSS Protips

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

  1. Use :not() to Apply/Unapply Borders on Navigation
  2. Add Line-Height to body
  3. Vertically Center Anything
  4. Select Items Using Negative nth-child
  5. Use SVG for Icons
  6. Inherit box-sizing
  7. Get Rid of Margin Hacks With Flexbox

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

/* instead of putting on the border... */
.nav li {
  border-right: 1px solid #666;
}

/* ...and then taking it off... */
.nav li:last-child {
  border-right: 0;
}

/* ...use :not() to only apply to the elements you want */
.nav li:not(:last-child) {
  border-right: 1px solid #666;
}

It's clean, readable, and easy to understand without the need for hack-y code.

Add Line-Height to body

body {
  line-height: 1;
}

You don't need to add line-height to each <p>, <h*>, et al. separately. This way textual elements can inherit from body easily.

Vertically Center Anything

html, body {
  height: 100%;
  margin: 0;
}

body {
  -webkit-align-items: center;  
  -ms-flex-align: center;  
  align-items: center;
  display: -webkit-flex;
  display: flex;
}

No, it's not dark magic, you really can center elements vertically. Look how simple this is.

Select Items Using Negative nth-child

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

Use negative nth-child in CSS to select items 1 through n. Well that was pretty easy.

Use SVG for Icons

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

There's no reason not to use SVG for icons. SVG is supported in all browsers back to IE9. So start ditching your .png, .jpg, or .gif-jif-whatev files.

Inherit box-sizing

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

Letting box-sizing be inheritted from html makes it easier to change box-sizing in plugins or other components that leverage other behavior.

Get Rid of Margin Hacks With Flexbox

.list-of-people {
  display: flex;
  justify-content: space-between;
}
.list-of-people .person {
  flex-basis: 23%;
}

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

Support

These protips work in current versions of Chrome, Firefox, Safari, and Edge, and in IE11.

About

A collection of useful CSS protips

License:MIT License