diff --git a/.babelrc b/.babelrc deleted file mode 100644 index f2e312799..000000000 --- a/.babelrc +++ /dev/null @@ -1,3 +0,0 @@ -{ - "presets": ["env", "stage-2"] -} diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..cf01b6ad4 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,8 @@ +src/docs/* linguist-documentation +scripts/* linguist-documentation +gatsby-browser.js linguist-documentation +gatsby-config.js linguist-documentation +gatsby-node.js linguist-documentation +gatsby-ssr.js linguist-documentation +.travis/* linguist-documentation +config.js linguist-documentation diff --git a/.gitignore b/.gitignore index ae7a50935..29d9977a5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,73 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) +build/Release + +# Dependency directories node_modules/ +jspm_packages/ + +# TypeScript v1 declaration files +typings/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn +yarn-error.log +.pnp/ +.pnp.js + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env + +# next.js build output +.next + +# gatsby files .cache/ -.DS_Store -dist/ +public + +# Mac files +.DS_Store \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index 0a3613911..cc831c8ff 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,16 +1,13 @@ language: node_js -node_js: - - node -install: - - npm install -script: - - npm run build -after_script: - - test $TRAVIS_EVENT_TYPE = cron - && echo -e "\e[95mDeploying to Repository" - && chmod +x .travis/push.sh - && ./.travis/push.sh - - chmod +x .travis/forcepush.sh && ./.travis/forcepush.sh cache: directories: - - node_modules \ No newline at end of file + - node_modules +node_js: +- lts/* +script: +- npm run linter +- npm run extractor +- npm run builder +after_success: +- chmod +x .travis/push.sh +- .travis/push.sh \ No newline at end of file diff --git a/.travis/forcepush.sh b/.travis/forcepush.sh deleted file mode 100644 index 54f15f5a5..000000000 --- a/.travis/forcepush.sh +++ /dev/null @@ -1,3 +0,0 @@ -if [[ $TRAVIS_COMMIT_MESSAGE == *"--force-build"* ]]; - then echo -e "\e[95mFORCE-DEPLOY: Deploying to Repository" && chmod +x .travis/push.sh && ./.travis/push.sh; -fi diff --git a/.travis/push.sh b/.travis/push.sh index a6c1eb6b1..fdd85ca67 100644 --- a/.travis/push.sh +++ b/.travis/push.sh @@ -12,8 +12,10 @@ commit_website_files() { git add * if [ $TRAVIS_EVENT_TYPE == "cron" ]; then git commit --message "Travis build: $TRAVIS_BUILD_NUMBER [cron]" + elif [ $TRAVIS_EVENT_TYPE == "api" ]; then + git commit --message "Travis build: $TRAVIS_BUILD_NUMBER [custom]" else - git commit --message "Travis build: $TRAVIS_BUILD_NUMBER [FORCED]" + git commit --message "Travis build: $TRAVIS_BUILD_NUMBER" fi fi fi diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0f6746904..45cbfd919 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,34 +1,43 @@ -### Snippet name +# Contribution guidelines -Brief description +**30 seconds of CSS** is a community effort, so feel free to contribute in any way you can. Every contribution helps! -#### HTML +Here's what you can do to help: -```html +- Submit [pull requests](https://github.com/30-seconds/30-seconds-of-css/pulls) with snippets and tests that you have created (see below for guidelines). +- [Open issues](https://github.com/30-seconds/30-seconds-of-css/issues/new) for things you want to see added or modified. +- Be part of the discussion by helping out with [existing issues](https://github.com/30-seconds/30-seconds-of-css/issues). +- Tag uncategorized snippets by adding the appropriate in the snippet's frontmatter in `tags`. +- Fix typos in existing snippets, improve snippet descriptions and explanations or provide better examples. -``` +### Snippet submission and Pull request guidelines -#### CSS - -```css -``` - -#### Demo - - - -#### Explanation - - - -#### Browser support - - - -⚠️ Caveat? - - - -- https://caniuse.com/#feat=some-feature - - +- **DO NOT MODIFY THE README.md FILE!** Make changes to individual snippet files. **Travis CI** will automatically build the `README.md` file when your pull request is merged. +- **Snippet filenames** must correspond to the title of the snippet. For example, if your snippet is titled `awesomeSnippet` the filename should be `awesomeSnippet.md`. + - Use `camelCase` or `kebab-case`, not `snake_case`. + - Avoid capitalization of words, except if the whole word is capitalized (e.g. `URL` should be capitalized in the filename and the snippet title). +- **Snippet metadata** must be included in all snippets in the form of frontmatter. + - All snippets must contain a title. + - All snippets must contain tags, prefixed with `tags:` and separated by commas (optional spaces in-between). + - Make sure the first tag in your snippet's tags is one of the main categories, as seen in the `README.md` file or the website. + - Snippet tags must include a difficulty setting (`begginer`, `intermediate` or `advanced`), preferrably at the end of the list. +- **Snippet titles** should be the same as the name of the function that is present in the snippet. + - All snippet titles must be prefixed with `title:` and be at the very first line of your snippet's frontmatter. + - Snippet titles must be unique (although if you cannot find a better title, just add some placeholder at the end of the filename and title and we will figure it out). + - Follow snippet titles with an empty line. +- **Snippet descriptions** must be short and to the point. Try to explain *what* the snippet does and *how* the snippet works and what Javascript features are used. Remember to include what functions you are using and why. + - Follow snippet descriptions with an empty line. +- **Snippet code** must be enclosed inside ` ```html `, ` ```css ` or ` ```js ` and ` ``` `. + - Remember to start your snippet's code on a new line below the opening backticks. + - Please use Javascript [Semi-Standard Style](https://github.com/Flet/semistandard). + - Try to keep your snippet's code short and to the point. Use modern techniques and features. Make sure to test your code before submitting. + - Try to make your snippet's name unique, so that it does not conflict with existing snippets. +- **Snippet explanations** should be written as lists of points, describing the implemented functionality. + - Use unordered lists if you have a few points, otherwise use an ordered list. + - If you have JavaScript functionality in your snippet, it might be worthwhile separating the explanation with it, by adding a new list or a horizontal line break (`---`). +- **Snippet browser support** should be specified as a list of links to https://www.caniuse.com/ features. + - Use the `#` next to the feature that you want in the website to get a link to it. +- Snippets should be short. If your snippet is long, you can still submit it, and we can help you shorten it or figure out ways to improve it. +- Snippets *should* solve real-world problems, no matter how simple. +- Snippets *should* be abstract enough to be applied to different scenarios. +- You can start creating a new snippet, by using the [snippet template](snippet-template.md) to format your snippets. diff --git a/README.md b/README.md index 6ef0d137c..9ca5a3fee 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,15 @@ # 30 Seconds of CSS -![logo](https://i.imgur.com/kPMfyD4.jpg) +![logo](https://i.imgur.com/kPMfyD4.jpg) [![License](https://img.shields.io/badge/license-CC0--1.0-blue.svg)](https://github.com/30-seconds/30-seconds-of-css/blob/master/LICENSE) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](http://makeapullrequest.com) [![Insight.io](https://img.shields.io/badge/insight.io-Ready-brightgreen.svg)](https://insight.io/github.com/30-seconds/30-seconds-of-css/tree/master/?source=0) A curated collection of useful CSS snippets you can understand in 30 seconds or less. -Inspired by [30 seconds of code](https://github.com/Chalarangelo/30-seconds-of-code). +Inspired by [30 seconds of code](https://github.com/30-seconds/30-seconds-of-code). ## View online -https://30-seconds.github.io/30-seconds-of-css/ +https://css.30secondsofcode.org ## Contributing @@ -20,3 +20,2418 @@ See CONTRIBUTING.md for the snippet template. - [30 Seconds of Code](https://30secondsofcode.org/) - [30 Seconds of Interviews](https://30secondsofinterviews.org/) - [30 Seconds of React](https://github.com/30-seconds/30-seconds-of-react) + +### Animation + +
+View contents + +* [`Bouncing loader`](#bouncing-loader) +* [`Button border animation`](#button-border-animation) +* [`Donut spinner`](#donut-spinner) +* [`Easing variables`](#easing-variables) +* [`Height transition`](#height-transition) +* [`Hover shadow box animation`](#hover-shadow-box-animation) +* [`Hover underline animation`](#hover-underline-animation) + +
+ +### Interactivity + +
+View contents + +* [`Disable selection`](#disable-selection) +* [`Popout menu`](#popout-menu) +* [`Sibling fade`](#sibling-fade) + +
+ +### Layout + +
+View contents + +* [`Box-sizing reset`](#box-sizing-reset) +* [`Clearfix`](#clearfix) +* [`Constant width to height ratio`](#constant-width-to-height-ratio) +* [`Display table centering`](#display-table-centering) +* [`Evenly distributed children`](#evenly-distributed-children) +* [`Fit image in container`](#fit-image-in-container) +* [`Flexbox centering`](#flexbox-centering) +* [`Ghost trick`](#ghost-trick) +* [`Grid centering`](#grid-centering) +* [`Last item with remaining available height`](#last-item-with-remaining-available-height) +* [`Offscreen`](#offscreen) +* [`Transform centering`](#transform-centering) +* [`Truncate text multiline`](#truncate-text-multiline) +* [`Truncate text`](#truncate-text) + +
+ +### Other + +
+View contents + +* [`Calc()`](#calc) +* [`Custom variables`](#custom-variables) + +
+ +### Visual + +
+View contents + +* [`Circle`](#circle) +* [`Counter`](#counter) +* [`Custom scrollbar`](#custom-scrollbar) +* [`Custom text selection`](#custom-text-selection) +* [`Dynamic shadow`](#dynamic-shadow) +* [`Etched text`](#etched-text) +* [`Focus Within`](#focus-within) +* [`Fullscreen`](#fullscreen) +* [`Gradient text`](#gradient-text) +* [`Hairline border`](#hairline-border) +* [`Mouse cursor gradient tracking`](#mouse-cursor-gradient-tracking) +* [`:not selector`](#not-selector) +* [`Overflow scroll gradient`](#overflow-scroll-gradient) +* [`Pretty text underline`](#pretty-text-underline) +* [`Reset all styles`](#reset-all-styles) +* [`Shape separator`](#shape-separator) +* [`System font stack`](#system-font-stack) +* [`Toggle switch`](#toggle-switch) +* [`Triangle`](#triangle) +* [`Zebra striped list`](#zebra-striped-list) + +
+ + +--- + +## Animation + + +### Bouncing loader + +Creates a bouncing loader animation. + +```html +
+
+
+
+
+``` + +```css +@keyframes bouncing-loader { + to { + opacity: 0.1; + transform: translate3d(0, -1rem, 0); + } +} +.bouncing-loader { + display: flex; + justify-content: center; +} +.bouncing-loader > div { + width: 1rem; + height: 1rem; + margin: 3rem 0.2rem; + background: #8385aa; + border-radius: 50%; + animation: bouncing-loader 0.6s infinite alternate; +} +.bouncing-loader > div:nth-child(2) { + animation-delay: 0.2s; +} +.bouncing-loader > div:nth-child(3) { + animation-delay: 0.4s; +} +``` + + +#### Explanation + + +Note: `1rem` is usually `16px`. + +1. `@keyframes` defines an animation that has two states, where the element changes `opacity` and is translated up on the 2D plane using `transform: translate3d()`. Using a single axis translation on `transform: translate3d()` improves the performance of the animation. +2. `.bouncing-loader` is the parent container of the bouncing circles and uses `display: flex` and `justify-content: center` to position them in the center. +3. `.bouncing-loader > div`, targets the three child `div`s of the parent to be styled. The `div`s are given a width and height of `1rem`, using `border-radius: 50%` to turn them from squares to circles. +4. `margin: 3rem 0.2rem` specifies that each circle has a top/bottom margin of `3rem` and left/right margin of `0.2rem` so that they do not directly touch each other, giving them some breathing room. +5. `animation` is a shorthand property for the various animation properties: `animation-name`, `animation-duration`, `animation-iteration-count`, `animation-direction` are used. +6. `nth-child(n)` targets the element which is the nth child of its parent. +7. `animation-delay` is used on the second and third `div` respectively, so that each element does not start the animation at the same time. + + +#### Browser support + +100.0% + +- https://caniuse.com/#feat=css-animation + + + + +
[⬆ Back to top](#contents) + +### Button border animation + +Creates a border animation on hover. + +```html +
+``` + +```css +.button { + background-color: #c47135; + border: none; + color: #ffffff; + outline: none; + padding: 12px 40px 10px; + position: relative; +} +.button:before, +.button:after { + border: 0 solid transparent; + transition: all 0.25s; + content: ''; + height: 24px; + position: absolute; + width: 24px; +} +.button:before { + border-top: 2px solid #c47135; + left: 0px; + top: -5px; +} +.button:after { + border-bottom: 2px solid #c47135; + bottom: -5px; + right: 0px; +} +.button:hover { + background-color: #c47135; +} +.button:hover:before, +.button:hover:after { + height: 100%; + width: 100%; +} +``` + + +#### Explanation + + +- Use the `:before` and `:after` pseduo-elements as borders that animate on hover. + + +#### Browser support + +100.0% + +
[⬆ Back to top](#contents) + +### Donut spinner + +Creates a donut spinner that can be used to indicate the loading of content. + +```html +
+``` + +```css +@keyframes donut-spin { + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(360deg); + } +} +.donut { + display: inline-block; + border: 4px solid rgba(0, 0, 0, 0.1); + border-left-color: #7983ff; + border-radius: 50%; + width: 30px; + height: 30px; + animation: donut-spin 1.2s linear infinite; +} +``` + + +#### Explanation + + +- Use a semi-transparent `border` for the whole element, except one side that will serve as the loading indicator for the donut. Use `animation` to rotate the element. + + +#### Browser support + +100.0% + +⚠️ Requires prefixes for full support. + +- https://caniuse.com/#feat=css-animation +- https://caniuse.com/#feat=transforms2d + + + + +
[⬆ Back to top](#contents) + +### Easing variables + +Variables that can be reused for `transition-timing-function` properties, more +powerful than the built-in `ease`, `ease-in`, `ease-out` and `ease-in-out`. + +```html +
Hover
+``` + +```css +:root { + /* Place variables in here to use globally */ +} + +.easing-variables { + --ease-in-quad: cubic-bezier(0.55, 0.085, 0.68, 0.53); + --ease-in-cubic: cubic-bezier(0.55, 0.055, 0.675, 0.19); + --ease-in-quart: cubic-bezier(0.895, 0.03, 0.685, 0.22); + --ease-in-quint: cubic-bezier(0.755, 0.05, 0.855, 0.06); + --ease-in-expo: cubic-bezier(0.95, 0.05, 0.795, 0.035); + --ease-in-circ: cubic-bezier(0.6, 0.04, 0.98, 0.335); + + --ease-out-quad: cubic-bezier(0.25, 0.46, 0.45, 0.94); + --ease-out-cubic: cubic-bezier(0.215, 0.61, 0.355, 1); + --ease-out-quart: cubic-bezier(0.165, 0.84, 0.44, 1); + --ease-out-quint: cubic-bezier(0.23, 1, 0.32, 1); + --ease-out-expo: cubic-bezier(0.19, 1, 0.22, 1); + --ease-out-circ: cubic-bezier(0.075, 0.82, 0.165, 1); + + --ease-in-out-quad: cubic-bezier(0.455, 0.03, 0.515, 0.955); + --ease-in-out-cubic: cubic-bezier(0.645, 0.045, 0.355, 1); + --ease-in-out-quart: cubic-bezier(0.77, 0, 0.175, 1); + --ease-in-out-quint: cubic-bezier(0.86, 0, 0.07, 1); + --ease-in-out-expo: cubic-bezier(1, 0, 0, 1); + --ease-in-out-circ: cubic-bezier(0.785, 0.135, 0.15, 0.86); + display: inline-block; + width: 75px; + height: 75px; + padding: 10px; + color: white; + line-height: 50px; + text-align: center; + background: #333; + transition: transform 1s var(--ease-out-quart); +} + +.easing-variables:hover { + transform: rotate(45deg); +} +``` + + +#### Explanation + + +- The variables are defined globally within the `:root` CSS pseudo-class which matches the root element of a tree representing the document. +- In HTML, `:root` represents the `` element and is identical to the selector `html`, except that its specificity is higher. + + +#### Browser support + +96.5% + +- https://caniuse.com/#feat=css-variables + + + + +
[⬆ Back to top](#contents) + +### Height transition + +Transitions an element's height from `0` to `auto` when its height is unknown. + +```html +
+ Hover me to see a height transition. +
content
+
+``` + +```css +.el { + transition: max-height 0.5s; + overflow: hidden; + max-height: 0; +} + +.trigger:hover > .el { + max-height: var(--max-height); +} +``` + +```js +var el = document.querySelector('.el') +var height = el.scrollHeight +el.style.setProperty('--max-height', height + 'px') +``` + + +#### Explanation + + +1. `transition: max-height: 0.5s cubic-bezier(...)` specifies that changes to `max-height` should be transitioned over 0.5 seconds, using an `ease-out-quint` timing function. +2. `overflow: hidden` prevents the contents of the hidden element from overflowing its container. +3. `max-height: 0` specifies that the element has no height initially. +4. `.target:hover > .el` specifies that when the parent is hovered over, target a child `.el` within it and use the `--max-height` variable which was defined by JavaScript. +--- +1. `el.scrollHeight` is the height of the element including overflow, which will change dynamically based on the content of the element. +2. `el.style.setProperty(...)` sets the `--max-height` CSS variable which is used to specify the `max-height` of the element the target is hovered over, allowing it to transition smoothly from 0 to auto. + + +#### Browser support + +96.5% + +
Requires JavaScript
+ + ⚠️ Causes reflow on each animation frame, which will be laggy if there are a large number of elements + beneath the element that is transitioning in height. + + +- https://caniuse.com/#feat=css-variables +- https://caniuse.com/#feat=css-transitions + + + + +
[⬆ Back to top](#contents) + +### Hover shadow box animation + +Creates a shadow box around the text when it is hovered. + +```html +

Box it!

+``` + +```css +.hover-shadow-box-animation { + display: inline-block; + vertical-align: middle; + transform: perspective(1px) translateZ(0); + box-shadow: 0 0 1px transparent; + margin: 10px; + transition-duration: 0.3s; + transition-property: box-shadow, transform; +} +.hover-shadow-box-animation:hover, +.hover-shadow-box-animation:focus, +.hover-shadow-box-animation:active { + box-shadow: 1px 10px 10px -10px rgba(0, 0, 24, 0.5); + transform: scale(1.2); +} +``` + + +#### Explanation + + +1. `display: inline-block` to set width and length for `p` element thus making it an `inline-block`. +2. Set `transform: perspective(1px)` to give element a 3D space by affecting the distance between the Z plane and the user and `translate(0)` to reposition the `p` element along z-axis in 3D space. +3. `box-shadow:` to set up the box. +4. `transparent` to make box transparent. +5. `transition-property` to enable transitions for both `box-shadow` and `transform`. +6. `:hover` to activate whole css when hovering is done until `active`. +7. `transform: scale(1.2)` to change the scale, magnifying the text. + + +#### Browser support + +100.0% + +- https://caniuse.com/#feat=transforms3d +- https://caniuse.com/#feat=css-transitions + + + + +
[⬆ Back to top](#contents) + +### Hover underline animation + +Creates an animated underline effect when the text is hovered over. + +**Credit:** https://flatuicolors.com/ + +```html +

Hover this text to see the effect!

+``` + +```css +.hover-underline-animation { + display: inline-block; + position: relative; + color: #0087ca; +} +.hover-underline-animation::after { + content: ''; + position: absolute; + width: 100%; + transform: scaleX(0); + height: 2px; + bottom: 0; + left: 0; + background-color: #0087ca; + transform-origin: bottom right; + transition: transform 0.25s ease-out; +} +.hover-underline-animation:hover::after { + transform: scaleX(1); + transform-origin: bottom left; +} +``` + + +#### Explanation + + +1. `display: inline-block` makes the block `p` an `inline-block` to prevent the underline from spanning the entire parent width rather than just the content (text). +2. `position: relative` on the element establishes a Cartesian positioning context for pseudo-elements. +3. `::after` defines a pseudo-element. +4. `position: absolute` takes the pseudo element out of the flow of the document and positions it in relation to the parent. +5. `width: 100%` ensures the pseudo-element spans the entire width of the text block. +6. `transform: scaleX(0)` initially scales the pseudo element to 0 so it has no width and is not visible. +7. `bottom: 0` and `left: 0` position it to the bottom left of the block. +8. `transition: transform 0.25s ease-out` means changes to `transform` will be transitioned over 0.25 seconds with an `ease-out` timing function. +9. `transform-origin: bottom right` means the transform anchor point is positioned at the bottom right of the block. +10. `:hover::after` then uses `scaleX(1)` to transition the width to 100%, then changes the `transform-origin` to `bottom left` so that the anchor point is reversed, allowing it transition out in the other direction when hovered off. + + +#### Browser support + +100.0% + +- https://caniuse.com/#feat=transforms2d +- https://caniuse.com/#feat=css-transitions + + + + +
[⬆ Back to top](#contents) + +--- + +## Interactivity + + +### Disable selection + +Makes the content unselectable. + +```html +

You can select me.

+

You can't select me!

+``` + +```css +.unselectable { + user-select: none; +} +``` + + +#### Explanation + + +- `user-select: none` specifies that the text cannot be selected. + + +#### Browser support + +97.5% + +⚠️ Requires prefixes for full support. +
+⚠️ This is not a secure method to prevent users from copying content. + +- https://caniuse.com/#feat=user-select-none + + + + +
[⬆ Back to top](#contents) + +### Popout menu + +Reveals an interactive popout menu on hover and focus. + +```html +
Popout menu
+``` + +```css +.reference { + position: relative; + background: tomato; + width: 100px; + height: 100px; +} +.popout-menu { + position: absolute; + visibility: hidden; + left: 100%; + background: #333; + color: white; + padding: 15px; +} +.reference:hover > .popout-menu, +.reference:focus > .popout-menu, +.reference:focus-within > .popout-menu { + visibility: visible; +} +``` + + +#### Explanation + + +1. `position: relative` on the reference parent establishes a Cartesian positioning context for its child. +2. `position: absolute` takes the popout menu out of the flow of the document and positions it in relation to the parent. +3. `left: 100%` moves the the popout menu 100% of its parent's width from the left. +4. `visibility: hidden` hides the popout menu initially and allows for transitions (unlike `display: none`). +5. `.reference:hover > .popout-menu` means that when `.reference` is hovered over, select immediate children with a class of `.popout-menu` and change their `visibility` to `visible`, which shows the popout. +6. `.reference:focus > .popout-menu` means that when `.reference` is focused, the popout would be shown. +7. `.reference:focus-within > .popout-menu` ensures that the popout is shown when the focus is _within_ the reference. + + +#### Browser support + +100.0% + + + + +
[⬆ Back to top](#contents) + +### Sibling fade + +Fades out the siblings of a hovered item. + +```html +
+ Item 1 Item 2 Item 3 Item 4 + Item 5 Item 6 +
+``` + +```css +span { + padding: 0 1rem; + transition: opacity 0.2s; +} + +.sibling-fade:hover span:not(:hover) { + opacity: 0.5; +} +``` + + +#### Explanation + + +1. `transition: opacity 0.2s` specifies that changes to opacity will be transitioned over 0.2 seconds. +2. `.sibling-fade:hover span:not(:hover)` specifies that when the parent is hovered, select any `span` children that are not currently being hovered and change their opacity to `0.5`. + + +#### Browser support + +100.0% + +- https://caniuse.com/#feat=css-sel3 +- https://caniuse.com/#feat=css-transitions + + + + +
[⬆ Back to top](#contents) + +--- + +## Layout + + +### Box-sizing reset + +Resets the box-model so that `width`s and `height`s are not affected by their `border`s or `padding`. + +```html +
border-box
+
content-box
+``` + +```css +html { + box-sizing: border-box; +} +*, +*::before, +*::after { + box-sizing: inherit; +} +.box { + display: inline-block; + width: 150px; + height: 150px; + padding: 10px; + background: tomato; + color: white; + border: 10px solid red; +} +.content-box { + box-sizing: content-box; +} +``` + + +#### Explanation + + +1. `box-sizing: border-box` makes the addition of `padding` or `border`s not affect an element's `width` or `height`. +2. `box-sizing: inherit` makes an element respect its parent's `box-sizing` rule. + + +#### Browser support + +100.0% + +- https://caniuse.com/#feat=css3-boxsizing + + + + +
[⬆ Back to top](#contents) + +### Clearfix + +Ensures that an element self-clears its children. + +###### Note: This is only useful if you are still using float to build layouts. Please consider using a modern approach with flexbox layout or grid layout. + +```html +
+
float a
+
float b
+
float c
+
+``` + +```css +.clearfix::after { + content: ''; + display: block; + clear: both; +} + +.floated { + float: left; +} +``` + + +#### Explanation + + +1. `.clearfix::after` defines a pseudo-element. +2. `content: ''` allows the pseudo-element to affect layout. +3. `clear: both` indicates that the left, right or both sides of the element cannot be adjacent to earlier floated elements within the same block formatting context. + + +#### Browser support + +100.0% + +⚠️ For this snippet to work properly you need to ensure that there are no non-floating children in the container and that there are no tall floats before the clearfixed container but in the same formatting context (e.g. floated columns). + + + + +
[⬆ Back to top](#contents) + +### Constant width to height ratio + +Given an element of variable width, it will ensure its height remains proportionate in a responsive fashion +(i.e., its width to height ratio remains constant). + +```html +
+``` + +```css +.constant-width-to-height-ratio { + background: #333; + width: 50%; +} +.constant-width-to-height-ratio::before { + content: ''; + padding-top: 100%; + float: left; +} +.constant-width-to-height-ratio::after { + content: ''; + display: block; + clear: both; +} +``` + + +#### Explanation + + +- `padding-top` on the `::before` pseudo-element causes the height of the element to equal a percentage of its width. `100%` therefore means the element's height will always be `100%` of the width, creating a responsive square. +- This method also allows content to be placed inside the element normally. + + +#### Browser support + +100.0% + + + + +
[⬆ Back to top](#contents) + +### Display table centering + +Vertically and horizontally centers a child element within its parent element using `display: table` (as an alternative to `flexbox`). + +```html +
+
Centered content
+
+``` + +```css +.container { + border: 1px solid #333; + height: 250px; + width: 250px; +} + +.center { + display: table; + height: 100%; + width: 100%; +} + +.center > span { + display: table-cell; + text-align: center; + vertical-align: middle; +} +``` + + +#### Explanation + + +1. `display: table` on '.center' allows the element to behave like a `` HTML element. +2. 100% height and width on '.center' allows the element to fill the available space within its parent element. +3. `display: table-cell` on '.center > span' allows the element to behave like an
HTML element. +4. `text-align: center` on '.center > span' centers the child element horizontally. +5. `vertical-align: middle` on '.center > span' centers the child element vertically. + +- The outer parent ('.container' in this case) must have a fixed height and width. + + +#### Browser support + +100.0% + +- https://caniuse.com/#search=display%3A%20table + + + + +
[⬆ Back to top](#contents) + +### Evenly distributed children + +Evenly distributes child elements within a parent element. + +```html +
+

Item1

+

Item2

+

Item3

+
+``` + +```css +.evenly-distributed-children { + display: flex; + justify-content: space-between; +} +``` + + +#### Explanation + + +1. `display: flex` enables flexbox. +2. `justify-content: space-between` evenly distributes child elements horizontally. The first item is positioned at the left edge, while the last item is positioned at the right edge. + +- Alternatively, use `justify-content: space-around` to distribute the children with space around them, rather than between them. + + +#### Browser support + +100.0% + +⚠️ Needs prefixes for full support. + +- https://caniuse.com/#feat=flexbox + + + + +
[⬆ Back to top](#contents) + +### Fit image in container + +Changes the fit and position of an image within its container while preserving its aspect ratio. Previously only possible using a background image and the `background-size` property. + +```html + + +``` + +```css +.image { + background: #34495e; + border: 1px solid #34495e; + width: 200px; + height: 200px; +} + +.image-contain { + object-fit: contain; + object-position: center; +} + +.image-cover { + object-fit: cover; + object-position: right top; +} +``` + + +#### Explanation + + +- `object-fit: contain` fits the entire image within the container while preserving its aspect ratio. +- `object-fit: cover` fills the container with the image while preserving its aspect ratio. +- `object-position: [x] [y]` positions the image within the container. + + +#### Browser support + +99.5% + +- https://caniuse.com/#feat=object-fit + +
[⬆ Back to top](#contents) + +### Flexbox centering + +Horizontally and vertically centers a child element within a parent element using `flexbox`. + +```html +
Centered content.
+``` + +```css +.flexbox-centering { + display: flex; + justify-content: center; + align-items: center; + height: 100px; +} +``` + + +#### Explanation + + +1. `display: flex` enables flexbox. +2. `justify-content: center` centers the child horizontally. +3. `align-items: center` centers the child vertically. + + +#### Browser support + +100.0% + +⚠️ Needs prefixes for full support. + +- https://caniuse.com/#feat=flexbox + + + + +
[⬆ Back to top](#contents) + +### Ghost trick + +Vertically centers an element in another. + +```html +
+

Vertically centered without changing the position property.

+
+``` + +```css +.ghosting { + height: 300px; + background: #0ff; +} + +.ghosting:before { + content: ''; + display: inline-block; + height: 100%; + vertical-align: middle; +} + +p { + display: inline-block; + vertical-align: middle; +} +``` + + +#### Explanation + + +- Use the style of a `:before` pseudo-element to vertically align inline elements without changing their `position` property. + + +#### Browser support + +100.0% + +- https://caniuse.com/#feat=inline-block + + + + +
[⬆ Back to top](#contents) + +### Grid centering + +Horizontally and vertically centers a child element within a parent element using `grid`. + +```html +
Centered content.
+``` + +```css +.grid-centering { + display: grid; + justify-content: center; + align-items: center; + height: 100px; +} +``` + + +#### Explanation + + +1. `display: grid` enables grid. +2. `justify-content: center` centers the child horizontally. +3. `align-items: center` centers the child vertically. + + +#### Browser support + +97.3% + +- https://caniuse.com/#feat=css-grid + + + + +
[⬆ Back to top](#contents) + +### Last item with remaining available height + +Take advantage of available viewport space by giving the last element the remaining available space in current viewport, even when resizing the window. + +```html +
+
Div 1
+
Div 2
+
Div 3
+
+``` + +```css +html, +body { + height: 100%; + margin: 0; +} + +.container { + height: 100%; + display: flex; + flex-direction: column; +} + +.container > div:last-child { + background-color: tomato; + flex: 1; +} +``` + + +#### Explanation + + +1. `height: 100%` set the height of container as viewport height. +2. `display: flex` enables flexbox. +3. `flex-direction: column` set the direction of flex items' order from top to down. +4. `flex-grow: 1` the flexbox will apply remaining available space of container to last child element. + +- The parent must have a viewport height. `flex-grow: 1` could be applied to the first or second element, which will have all available space. + + +#### Browser support + +100.0% + +⚠️ Needs prefixes for full support. + +- https://caniuse.com/#feat=flexbox + +
[⬆ Back to top](#contents) + +### Offscreen + +A bulletproof way to completely hide an element visually and positionally in the DOM while still allowing it to be accessed by JavaScript and readable by screen readers. This method is very useful for accessibility ([ADA](https://adata.org/learn-about-ada)) development when more context is needed for visually-impaired users. As an alternative to `display: none` which is not readable by screen readers or `visibility: hidden` which takes up physical space in the DOM. + +```html + + Learn More about pants + +``` + +```css +.offscreen { + border: 0; + clip: rect(0 0 0 0); + height: 1px; + margin: -1px; + overflow: hidden; + padding: 0; + position: absolute; + width: 1px; +} +``` + + +#### Explanation + + +1. Remove all borders. +2. Use `clip` to indicate that no part of the element should be shown. +3. Make the height and width of the element 1px. +4. Negate the elements height and width using `margin: -1px`. +5. Hide the element's overflow. +6. Remove all padding. +7. Position the element absolutely so that it does not take up space in the DOM. + + +#### Browser support + +100.0% + +(Although `clip` technically has been depreciated, the newer `clip-path` currently has very limited browser support.) + +- https://caniuse.com/#search=clip + + + + +
[⬆ Back to top](#contents) + +### Transform centering + +Vertically and horizontally centers a child element within its parent element using `position: absolute` and `transform: translate()` (as an alternative to `flexbox` or `display: table`). Similar to `flexbox`, this method does not require you to know the height or width of your parent or child so it is ideal for responsive applications. + +```html +
Centered content
+``` + +```css +.parent { + border: 1px solid #333; + height: 250px; + position: relative; + width: 250px; +} + +.child { + left: 50%; + position: absolute; + top: 50%; + transform: translate(-50%, -50%); + text-align: center; +} +``` + + +#### Explanation + + +1. `position: absolute` on the child element allows it to be positioned based on its containing block. +2. `left: 50%` and `top: 50%` offsets the child 50% from the left and top edge of its containing block. +3. `transform: translate(-50%, -50%)` allows the height and width of the child element to be negated so that it is vertically and horizontally centered. + +- Note: that the fixed height and width on parent element is for the demo only. + + +#### Browser support + +100.0% + +⚠️ Requires prefix for full support. + +- https://caniuse.com/#feat=transforms2d + + + + +
[⬆ Back to top](#contents) + +### Truncate text multiline + +If the text is longer than one line, it will be truncated for `n` lines and end with an gradient fade. + +```html +

+ Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut + labore et. +

+``` + +```css +.truncate-text-multiline { + overflow: hidden; + display: block; + height: 109.2px; + margin: 0 auto; + font-size: 26px; + line-height: 1.4; + width: 400px; + position: relative; +} + +.truncate-text-multiline:after { + content: ''; + position: absolute; + bottom: 0; + right: 0; + width: 150px; + height: 36.4px; + background: linear-gradient(to right, rgba(0, 0, 0, 0), #f5f6f9 50%); +} +``` + + +#### Explanation + + +1. `overflow: hidden` prevents the text from overflowing its dimensions (for a block, 100% width and auto height). +2. `width: 400px` ensures the element has a dimension. +3. `height: 109.2px` calculated value for height, it equals `font-size * line-height * numberOfLines` (in this case `26 * 1.4 * 3 = 109.2`) +4. `height: 36.4px` calculated value for gradient container, it equals `font-size * line-height` (in this case `26 * 1.4 = 36.4`) +5. `background: linear-gradient(to right, rgba(0, 0, 0, 0), #f5f6f9 50%)` gradient from `transparent` to `#f5f6f9` + + +#### Browser support + +100.0% + +- https://caniuse.com/#feat=css-gradients + + + + +
[⬆ Back to top](#contents) + +### Truncate text + +If the text is longer than one line, it will be truncated and end with an ellipsis `…`. + +```html +

If I exceed one line's width, I will be truncated.

+``` + +```css +.truncate-text { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + width: 200px; +} +``` + + +#### Explanation + + +1. `overflow: hidden` prevents the text from overflowing its dimensions (for a block, 100% width and auto height). +2. `white-space: nowrap` prevents the text from exceeding one line in height. +3. `text-overflow: ellipsis` makes it so that if the text exceeds its dimensions, it will end with an ellipsis. +4. `width: 200px;` ensures the element has a dimension, to know when to get ellipsis + + +#### Browser support + +100.0% + +⚠️ Only works for single line elements. + +- https://caniuse.com/#feat=text-overflow + + + + +
[⬆ Back to top](#contents) + +--- + +## Other + + +### Calc() + +The function calc() allows to define CSS values with the use of mathematical expressions, the value adopted for the property is the result of a mathematical expression. + +```html +
+``` + +```css +.box-example { + height: 280px; + background: #222 url('https://image.ibb.co/fUL9nS/wolf.png') no-repeat; + background-position: calc(100% - 20px) calc(100% - 20px); +} +``` + + +#### Explanation + + +1. It allows addition, subtraction, multiplication and division. +2. Can use different units (pixel and percent together, for example) for each value in your expression. +3. It is permitted to nest calc() functions. +4. It can be used in any property that ``, ``, ``, `