diff --git a/CODE-OF-CONDUCT.md b/CODE-OF-CONDUCT.md index 1dca52b9..456fae5b 100644 --- a/CODE-OF-CONDUCT.md +++ b/CODE-OF-CONDUCT.md @@ -19,6 +19,6 @@ By adopting this Code of Conduct, project maintainers commit themselves to fairl This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. -Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting a project maintainer at mjsmithme@gmail.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. Maintainers are obligated to maintain confidentiality with regard to the reporter of an incident. +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project maintainer at mjsmithme@gmail.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. Maintainers are obligated to maintain confidentiality with regard to the reporter of an incident. This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.3.0, available at [http://contributor-covenant.org/version/1/3/0/](http://contributor-covenant.org/version/1/3/0/). \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e8c51f8e..7e011f42 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,43 +2,32 @@ Please note that this project is released with a [Contributor Code of Conduct](CODE-OF-CONDUCT.md). By participating in this project you agree to abide by its terms. - -## Table of Contents +## Contents - [Adding to This List](#adding-to-this-list) - [Updating Your Pull Request](#updating-your-pull-request) - ## Adding to This List Please ensure your pull request adheres to the following guidelines: -* Search open and closed PR's to avoid duplicate suggestions. -* Only submit CSS tips that you think would be useful to others. This implies each tip has enough succinct content to describe why it's useful. -* Add your tip at the bottom of the [README](https://github.com/AllThingsSmitty/css-protips/blob/master/README.md) document. Add a link to your tip at the bottom of the table of contents. -* Use [title-casing](http://titlecapitalization.com). -* Code formatting should follow standard [CSSLint](http://www.csslint.net) default settings, including: - * Indent with two spaces - * Use shorthand, e.g., `margin: 10px 10px 5px;` - * Use double quotes, e.g., `background: url("logo.svg");` - * Sort properties alphabetically -* Make sure your text editor is set to remove trailing whitespace. -* Check your spelling and grammar. -* The PR should have a useful title. +- Search open and closed PRs to avoid duplicate suggestions. +- Only submit CSS tips that you think would be useful to others. This implies each tip has enough succinct content to describe why it's useful. +- Add your tip at the bottom of the [README](https://github.com/AllThingsSmitty/css-protips/blob/master/README.md) document. Add a link to your tip at the bottom of the table of contents. +- Use [title-case](https://titlecaseconverter.com/). +- Code formatting should follow standard [CSSLint](http://www.csslint.net) default settings, including: + - Indent with two spaces + - Use shorthand, e.g., `margin: 10px 10px 0.5rem;` + - Use double quotes, e.g., `background: url("logo.svg");` + - Use leading zeros with numberic values, e.g., `padding: 0.75rem;` + - Sort properties alphabetically + - **Avoid letting your code formatter format other section of the README file.** +- Make sure your text editor is set to remove trailing whitespace. +- Check your spelling and grammar. +- The PR should have a useful title. Thank you for your suggestions! - -### Language Translations - -If you fluently speak another language and want to contribute by translating this list into that language, please submit a PR using the following guidelines: - -* Add a new folder to the `translations` folder -* The new folder should be labeled the language culture name, e.g, `es-ES`, `ru-RU`, `zh-CN`, etc. - -Additionally, feel free to review already translated content for accuracy. - - ## Updating Your Pull Request -Sometimes a maintainer will ask you to edit your pull request before it's included. This is normally due to spelling errors or because your PR didn't match the above guidlines guidelines. [This write-up](https://github.com/RichardLitt/docs/blob/master/amending-a-commit-guide.md) covers the different ways you can change a pull request. \ No newline at end of file +Sometimes a maintainer will ask you to edit your pull request before it's included. This is normally due to spelling errors or because your PR didn't match the above guidelines. [This write-up](https://github.com/RichardLitt/knowledge/blob/master/github/amending-a-commit-guide.md) covers the different ways you can change a pull request. diff --git a/README.md b/README.md index f366d304..514038b3 100644 --- a/README.md +++ b/README.md @@ -1,45 +1,122 @@ -

- light bulb icon -

+
+ light bulb icon +
-# CSS Protips [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) +# CSS Protips [![Awesome](https://awesome.re/badge-flat.svg)](https://awesome.re) A collection of tips to help take your CSS skills pro. +> [!TIP] > For other great lists check out [@sindresorhus](https://github.com/sindresorhus/)'s curated list of [awesome lists](https://github.com/sindresorhus/awesome/). +## Contents -## Table of Contents - -* [Protips](#protips) -* [Support](#support) -* [Translations](#translations) -* [Contribution Guidelines](CONTRIBUTING.md) - +- [Protips](#protips) +- [Support](#support) +- [Translations](#translations) +- [Contribution Guidelines](CONTRIBUTING.md) ## Protips +1. [Use a CSS Reset](#use-a-css-reset) +1. [Inherit `box-sizing`](#inherit-box-sizing) +1. [Use `unset` Instead of Resetting All Properties](#use-unset-instead-of-resetting-all-properties) 1. [Use `:not()` to Apply/Unapply Borders on Navigation](#use-not-to-applyunapply-borders-on-navigation) +1. [Check if Font Is Installed Locally](#check-if-font-is-installed-locally) 1. [Add `line-height` to `body`](#add-line-height-to-body) +1. [Set `:focus` for Form Elements](#set-focus-for-form-elements) 1. [Vertically-Center Anything](#vertically-center-anything) +1. [Use `aspect-ratio` Instead of Height/Width](#use-aspect-ratio-instead-of-heightwidth) 1. [Comma-Separated Lists](#comma-separated-lists) 1. [Select Items Using Negative `nth-child`](#select-items-using-negative-nth-child) 1. [Use SVG for Icons](#use-svg-for-icons) 1. [Use the "Lobotomized Owl" Selector](#use-the-lobotomized-owl-selector) 1. [Use `max-height` for Pure CSS Sliders](#use-max-height-for-pure-css-sliders) -1. [Inherit `box-sizing`](#inherit-box-sizing) -1. [Equal Width Table Cells](#equal-width-table-cells) +1. [Equal-Width Table Cells](#equal-width-table-cells) 1. [Get Rid of Margin Hacks With Flexbox](#get-rid-of-margin-hacks-with-flexbox) 1. [Use Attribute Selectors with Empty Links](#use-attribute-selectors-with-empty-links) +1. [Control Specificity Better With `:is()`](#control-specificity-better-with-is) 1. [Style "Default" Links](#style-default-links) -1. [Consistent Vertical Rhythm](#consistent-vertical-rhythm) 1. [Intrinsic Ratio Boxes](#intrinsic-ratio-boxes) 1. [Style Broken Images](#style-broken-images) 1. [Use `rem` for Global Sizing; Use `em` for Local Sizing](#use-rem-for-global-sizing-use-em-for-local-sizing) 1. [Hide Autoplay Videos That Aren't Muted](#hide-autoplay-videos-that-arent-muted) 1. [Use `:root` for Flexible Type](#use-root-for-flexible-type) 1. [Set `font-size` on Form Elements for a Better Mobile Experience](#set-font-size-on-form-elements-for-a-better-mobile-experience) +1. [Use Pointer Events to Control Mouse Events](#use-pointer-events-to-control-mouse-events) +1. [Set `display: none` on Line Breaks Used as Spacing](#set-display-none-on-line-breaks-used-as-spacing) +1. [Use `:empty` to Hide Empty HTML Elements](#use-empty-to-hide-empty-html-elements) +1. [Use `margin-inline` instead of `margin`](#use-margin-inline-instead-of-margin) + +### 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: +```css +*, +*::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. + +#### [Demo](https://codepen.io/AllThingsSmitty/pen/kkrkLL) + +> [!TIP] +> If you follow the [Inherit `box-sizing`](#inherit-box-sizing) tip below you might opt to not include the `box-sizing` property in your CSS reset. + +[Back to top](#contents) + +### Inherit `box-sizing` + +Let `box-sizing` be inherited from `html`: + +```css +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. + +#### [Demo](https://css-tricks.com/inheriting-box-sizing-probably-slightly-better-best-practice/) + +[Back to top](#contents) + +### Use `unset` Instead of Resetting All Properties + +When resetting an element's properties, it's not necessary to reset each individual property: + +```css +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: + +```css +button { + all: unset; +} +``` + +[Back to top](#contents) ### Use `:not()` to Apply/Unapply Borders on Navigation @@ -69,10 +146,32 @@ Instead of putting on the border... } ``` -Sure, you can use `.nav li + li` or even `.nav li:first-child ~ li`, but with `:not()` the intent is very clear and the CSS selector defines the border the way a human would describe it. +Here, the CSS selector is read as a human would describe it. + +#### [Demo](https://codepen.io/AllThingsSmitty/pen/LkymvO) + +[Back to top](#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. + +```css +@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; +} +``` -[back to table of contents](#table-of-contents) +H/T to Adam Argyle for sharing this protip and [demo](https://codepen.io/argyleink/pen/VwYJpgR). +[Back to top](#contents) ### Add `line-height` to `body` @@ -86,34 +185,80 @@ body { This way textual elements can inherit from `body` easily. -[back to table of contents](#table-of-contents) +#### [Demo](https://codepen.io/AllThingsSmitty/pen/VjbdYd) + +[Back to top](#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: + +```css +a:focus, +button:focus, +input:focus, +select:focus, +textarea:focus { + box-shadow: none; + outline: #000 dotted 2px; + outline-offset: 0.05em; +} +``` + +#### [Demo](https://codepen.io/AllThingsSmitty/pen/ePzoOP/) +[Back to top](#contents) ### Vertically-Center Anything -No, it's not black magic, you really can center elements vertically: +No, it's not black magic, you really can center elements vertically. You can do this with flexbox... ```css -html, body { +html, +body { height: 100%; - margin: 0; } body { - -webkit-align-items: center; - -ms-flex-align: center; align-items: center; - display: -webkit-flex; display: flex; + justify-content: center; +} +``` + +...and also with CSS Grid: + +```css +body { + display: grid; + height: 100vh; + place-items: center; } ``` -Want to center something else? Vertically, horizontally...anything, anytime, anywhere? CSS-Tricks has [a nice write-up](https://css-tricks.com/centering-css-complete-guide/) on doing all of that. +> [!TIP] +> Want to center something else? Vertically, horizontally...anything, anytime, anywhere? CSS-Tricks has [a nice write-up](https://css-tricks.com/centering-css-complete-guide/) on doing all of that. + +#### [Demo](https://codepen.io/AllThingsSmitty/pen/GqmGqZ) -**Note:** Watch for some [buggy behavior](https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items) with flexbox in IE11. +[Back to top](#contents) -[back to table of contents](#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. + +```css +img { + aspect-ratio: 16 / 9; /* width / height */ + object-fit: cover; +} +``` + +Learn more about the `aspect-ratio` property in this [web.dev post](https://web.dev/articles/aspect-ratio). + +#### [Demo](https://codepen.io/AllThingsSmitty/pen/MWxwoNx/) + +[Back to top](#contents) ### Comma-Separated Lists @@ -125,12 +270,12 @@ ul > li:not(:last-child)::after { } ``` -Use the `:not()` pseudo-class so no comma is added to the last item. +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](#table-of-contents) +> [!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 top](#contents) ### Select Items Using Negative `nth-child` @@ -142,7 +287,7 @@ li { } /* select items 1 through 3 and display them */ -li:nth-child(-n+3) { +li:nth-child(-n + 3) { display: block; } ``` @@ -150,16 +295,15 @@ li:nth-child(-n+3) { Or, since you've already learned a little about [using `:not()`](#use-not-to-applyunapply-borders-on-navigation), try: ```css -/* select items 1 through 3 and display them */ -li:not(:nth-child(-n+3)) { - display: none; +/* select all items except the first 3 and display them */ +li:not(:nth-child(-n + 3)) { + display: block; } ``` -Well that was pretty easy. - -[back to table of contents](#table-of-contents) +#### [Demo](https://codepen.io/AllThingsSmitty/pen/WxjKZp) +[Back to top](#contents) ### Use SVG for Icons @@ -171,18 +315,18 @@ 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](http://caniuse.com/#search=svg). So ditch your .png, .jpg, or .gif-jif-whatev files. +SVG scales well for all resolution types and is supported in all browsers [back to IE9](http://caniuse.com/#search=svg). 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: +> [!NOTE] +> If you have SVG icon-only buttons for sighted users and the SVG fails to load, this will help maintain accessibility: ```css -.no-svg .icon-only:after { +.no-svg .icon-only::after { content: attr(aria-label); } ``` -[back to table of contents](#table-of-contents) - +[Back to top](#contents) ### Use the "Lobotomized Owl" Selector @@ -196,10 +340,12 @@ It may have a strange name but using the universal selector (`*`) with the adjac In this example, all elements in the flow of the document that follow other elements will receive `margin-top: 1.5em`. -For more on the "lobotomized owl" selector, read [Heydon Pickering's post](http://alistapart.com/article/axiomatic-css-and-lobotomized-owls) on *A List Apart*. +> [!TIP] +> For more on the "lobotomized owl" selector, read [Heydon Pickering's post](http://alistapart.com/article/axiomatic-css-and-lobotomized-owls) on _A List Apart_. -[back to table of contents](#table-of-contents) +#### [Demo](https://codepen.io/AllThingsSmitty/pen/grRvWq) +[Back to top](#contents) ### Use `max-height` for Pure CSS Sliders @@ -220,31 +366,11 @@ Implement CSS-only sliders using `max-height` with overflow hidden: 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](#table-of-contents) - - -### Inherit `box-sizing` - -Let `box-sizing` be inherited from `html`: - -```css -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](#table-of-contents) - +[Back to top](#contents) -### Equal Width Table Cells +### Equal-Width Table Cells -Tables can be a pain to work with so try using `table-layout: fixed` to keep cells at equal width: +Tables can be a pain to work with. Try using `table-layout: fixed` to keep cells at equal width: ```css .calendar { @@ -254,8 +380,9 @@ Tables can be a pain to work with so try using `table-layout: fixed` to keep cel Pain-free table layouts. -[back to table of contents](#table-of-contents) +#### [Demo](https://codepen.io/AllThingsSmitty/pen/jALALm) +[Back to top](#contents) ### Get Rid of Margin Hacks With Flexbox @@ -274,8 +401,7 @@ When working with column gutters you can get rid of `nth-`, `first-`, and `last- Now column gutters always appear evenly-spaced. -[back to table of contents](#table-of-contents) - +[Back to top](#contents) ### Use Attribute Selectors with Empty Links @@ -287,41 +413,74 @@ a[href^="http"]:empty::before { } ``` -That's pretty convenient. +That's really convenient. -[back to table of contents](#table-of-contents) +#### [Demo](https://codepen.io/AllThingsSmitty/pen/zBzXRx) +> [!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. -### Style "Default" Links +[Back to top](#contents) -Add a style for "default" links: +### 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. ```css -a[href]:not([class]) { - color: #008000; - text-decoration: underline; +:is(section, article, aside, nav) :is(h1, h2, h3, h4, h5, h6) { + color: green; } ``` -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. +The above ruleset is equivalent to the following number selector rules... -[back to table of contents](#table-of-contents) +```css +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; +} +``` +#### [Demo](https://codepen.io/AllThingsSmitty/pen/rNRVxdx) -### Consistent Vertical Rhythm +[Back to top](#contents) + +### Style "Default" Links -Use a universal selector (`*`) within an element to create a consistent vertical rhythm: +Add a style for "default" links: ```css -.intro > * { - margin-bottom: 1.25rem; +a[href]:not([class]) { + color: #008000; + text-decoration: underline; } ``` -Consistent vertical rhythm provides a visual aesthetic that makes content far more readable. - -[back to table of contents](#table-of-contents) +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 top](#contents) ### Intrinsic Ratio Boxes @@ -346,8 +505,9 @@ To create a box with an intrinsic ratio, all you need to do is apply top or bott 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](#table-of-contents) +#### [Demo](https://codepen.io/AllThingsSmitty/pen/jALZvE) +[Back to top](#contents) ### Style Broken Images @@ -356,7 +516,7 @@ Make broken images more aesthetically-pleasing with a little bit of CSS: ```css img { display: block; - font-family: Helvetica, Arial, sans-serif; + font-family: sans-serif; font-weight: 300; height: auto; line-height: 2; @@ -369,27 +529,27 @@ img { Now add pseudo-elements rules to display a user message and URL reference of the broken image: ```css -img:before { +img::before { content: "We're sorry, the image below is broken :("; display: block; margin-bottom: 10px; } -img:after { +img::after { content: "(url: " attr(src) ")"; display: block; font-size: 12px; } ``` -Learn more about styling for this pattern in [Ire Aderinokun](https://github.com/ireade/)'s [original post](http://bitsofco.de/styling-broken-images/). - -[back to table of contents](#table-of-contents) +> [!TIP] +> Learn more about styling for this pattern in [Ire Aderinokun's post](http://bitsofco.de/styling-broken-images/). +[Back to top](#contents) ### Use `rem` for Global Sizing; Use `em` for Local Sizing -After setting the base font size at the root (`html { font-size: 16px; }`), set the font size for textual elements to `em`: +After setting the base font size at the root (`html { font-size: 100%; }`), set the font size for textual elements to `em`: ```css h2 { @@ -409,14 +569,13 @@ article { } aside .module { - font-size: .9rem; + font-size: 0.9rem; } ``` Now each module becomes compartmentalized and easier to style, more maintainable, and flexible. -[back to table of contents](#table-of-contents) - +[Back to top](#contents) ### Hide Autoplay Videos That Aren't Muted @@ -430,8 +589,7 @@ video[autoplay]:not([muted]) { Once again, we're taking advantage of using the [`:not()`](#use-not-to-applyunapply-borders-on-navigation) pseudo-class. -[back to table of contents](#table-of-contents) - +[Back to top](#contents) ### Use `:root` for Flexible Type @@ -439,7 +597,7 @@ The type font size in a responsive layout should be able to adjust with each vie ```css :root { - font-size: calc(1vw + 1vh + .5vmin); + font-size: calc(1vw + 1vh + 0.5vmin); } ``` @@ -447,12 +605,13 @@ Now you can utilize the `root em` unit based on the value calculated by `:root`: ```css body { - font: 1em/1.6 sans-serif; + font: 1rem/1.6 sans-serif; } ``` -[back to table of contents](#table-of-contents) +#### [Demo](https://codepen.io/AllThingsSmitty/pen/XKgOkR) +[Back to top](#contents) ### Set `font-size` on Form Elements for a Better Mobile Experience @@ -467,20 +626,97 @@ textarea { } ``` -:dancer: +[Back to top](#contents) + +### Use Pointer Events to Control Mouse Events + +[Pointer events](https://developer.mozilla.org/en-US/docs/Web/CSS/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: + +```css +button:disabled { + opacity: 0.5; + pointer-events: none; +} +``` + +It's that simple. + +[Back to top](#contents) + +### Set `display: none` on Line Breaks Used as Spacing + +As [Harry Roberts pointed out](https://twitter.com/csswizardry/status/1170835532584235008), this can help prevent CMS users from using extra line breaks for spacing: + +```css +br + br { + display: none; +} +``` + +[Back to top](#contents) -[back to table of contents](#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., `

`) and it's creating unwanted space on your layout, use the `:empty` pseudo-class to hide the element on the layout. + +```css +:empty { + display: none; +} +``` + +> [!NOTE] +> Keep in mind that elements with whitespace aren't considered empty, e.g., `

`. + +[Back to top](#contents) ## Support -Current versions of Chrome, Firefox, Safari, Opera, Edge, and IE11. +Current versions of Chrome, Firefox, Safari, and Edge. + +[Back to top](#contents) + +### Use `margin-inline` instead of `margin` + +`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. + +```css +.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`. + +```css +.div { + margin-block: auto; +} +``` + +#### [Demo](https://codepen.io/AllThingsSmitty/pen/PwoOQGB) +[Back to top](#contents) ## Translations -* [Español](https://github.com/AllThingsSmitty/css-protips/tree/master/translations/es-ES) -* [Français](https://github.com/AllThingsSmitty/css-protips/tree/master/translations/fr-FR) -* [Português do Brasil](https://github.com/AllThingsSmitty/css-protips/tree/master/translations/pt-BR) -* [Русский](https://github.com/AllThingsSmitty/css-protips/tree/master/translations/ru-RU) -* [简体中文](https://github.com/AllThingsSmitty/css-protips/tree/master/translations/zh-CN) +> [!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. + +- [简体中文](https://github.com/AllThingsSmitty/css-protips/tree/master/translations/zh-CN) +- [正體中文](https://github.com/AllThingsSmitty/css-protips/tree/master/translations/zh-TW) +- [Deutsch](https://github.com/AllThingsSmitty/css-protips/tree/master/translations/de-DE) +- [Español](https://github.com/AllThingsSmitty/css-protips/tree/master/translations/es-ES) +- [Français](https://github.com/AllThingsSmitty/css-protips/tree/master/translations/fr-FR) +- [λληνικά](https://github.com/AllThingsSmitty/css-protips/tree/master/translations/gr-GR) +- [ગુજરાતી](https://github.com/AllThingsSmitty/css-protips/tree/master/translations/gu-IND) +- [Italiano](https://github.com/AllThingsSmitty/css-protips/tree/master/translations/it-IT) +- [日本語](https://github.com/AllThingsSmitty/css-protips/tree/master/translations/ja-JP) +- [한국어](https://github.com/AllThingsSmitty/css-protips/tree/master/translations/ko-KR) +- [Polskie](https://github.com/AllThingsSmitty/css-protips/tree/master/translations/pl-PL) +- [Português do Brasil](https://github.com/AllThingsSmitty/css-protips/tree/master/translations/pt-BR) +- [Português do Europe](https://github.com/AllThingsSmitty/css-protips/tree/master/translations/pt-PT) +- [Русский](https://github.com/AllThingsSmitty/css-protips/tree/master/translations/ru-RU) +- [Tiếng Việt](https://github.com/AllThingsSmitty/css-protips/tree/master/translations/vn-VN) + +[Back to top](#contents) diff --git a/media/logo.svg b/assets/img/bulb.svg similarity index 98% rename from media/logo.svg rename to assets/img/bulb.svg index 5ac5732e..7ea82da2 100644 --- a/media/logo.svg +++ b/assets/img/bulb.svg @@ -1,7 +1,7 @@ - + diff --git a/translations/de-DE/README.md b/translations/de-DE/README.md new file mode 100644 index 00000000..821701a2 --- /dev/null +++ b/translations/de-DE/README.md @@ -0,0 +1,624 @@ +

+ light bulb icon +

+ +# CSS Profi-Tipps [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) + +Eine Sammlung an Tipps, um deine CSS-Fähigkeiten zu professionalisieren. + +> Für andere großartige Listen schaue dir [@sindresorhus](https://github.com/sindresorhus/)s kuratierte Liste von ["awesome" Listen](https://github.com/sindresorhus/awesome/) an. + + +## Inhaltsverzeichnis + +* [Profi-Tipps](#profi-tipps) +* [Unterstützung](#unterstützung) +* [Mitarbeitsrichtlinien](../../CONTRIBUTING.md) + + +## Profi-Tipps + +1. [Benutze ein CSS-Reset](#benutze-ein-css-reset) +1. [Übernehme `box-sizing`](#Übernehme-box-sizing) +1. [Benutze `unset`, anstatt alle Eigenschaften zurückzusetzen](#benutze-unset-anstatt-alle-eigenschaften-zurückzusetzen) +1. [Benutze `:not()` um Rahmen an die Navigation zu setzen oder zu entfernen](#benutze-not-um-rahmen-an-die-navigation-zu-setzen-oder-zu-entfernen) +1. [Kontroller, om skrifttypen er installeret lokalt](#Kontroller-om-skrifttypen-er-installeret-lokalt) +1. [Ergänze `line-height` an `body`](#ergänze-line-height-an-body) +1. [Setze `:focus` für Form-Elemente](#setze-focus-für-form-elemente) +1. [Zentriere alles vertikal](#zentriere-alles-vertikal) +1. [Kommaseparierte Liste](#kommaseparierte-liste) +1. [Selektiere Items mit einem negativen `nth-child`](#selektiere-items-mit-einem-negativen-nth-child) +1. [Benutze SVG für Symbole](#benutze-svg-für-symbole) +1. [Benutze den "lobotomisierte Eule"-Selektor](#benutze-den-lobotomisierte-eule-selektor) +1. [Benutze `max-height` für reine CSS-Galerien](#benutze-max-height-für-reine-css-galerien) +1. [Setze Tabellenzellen auf die gleiche Weite](#setze-tabellenzellen-auf-die-gleiche-weite) +1. [Benutze Flexbox, um von Margin-Hacks wegzukommen](#benutze-flexbox-um-von-margin-hacks-wegzukommen) +1. [Benutze den Attribut-Selektor mit leeren Verlinkungen](#benutze-den-attribut-selektor-mit-leeren-verlinkungen) +1. [Gestalte "Standard"-Verlinkungen](#gestalte-standard-verlinkungen) +1. [Boxen mit zugehörigem Größenverhältnis](#boxen-mit-zugehörigem-größenverhältnis) +1. [Gestalte defekte Bilder](#gestalte-defekte-bilder) +1. [Benutze `rem` für globales Ändern der Größe; Benutze `em` für lokale Größenveränderungen](#benutze-rem-für-globales-Ändern-der-größe-benutze-em-für-lokale-größenveränderungen) +1. [Verstecke automatisch abspielende Videos, die nicht auf stumm gesetzt sind](#verstecke-automatisch-abspielende-videos-die-nicht-auf-stumm-gesetzt-sind) +1. [Benutze `:root` für flexible Schrift](#benutze-root-für-flexible-schrift) +1. [Setze `font-size` auf Formular-Elemente für eine bessere mobile Erfahrung](#setze-font-size-auf-formular-elemente-für-eine-bessere-mobile-erfahrung) +1. [Benutze `Pointer`-Events um Mausereignisse zu kontrollieren](#benutze-pointer-events-um-mausereignisse-zu-kontrollieren) +1. [Stellen Sie bei Zeilenumbrüchen, die als Abstand verwendet werden, `display: none` ein](#stellen-sie-bei-zeilenumbrüchen,-die-als-abstand-verwendet-werden-display-none-ein) + + +### Benutze ein CSS-Reset + +CSS Resets helfen dabei eine Gestaltungskonsistenz zwischen verschiedenen Browsern herzustellen, indem sie für einen sauberen Zustand zwischen den einzelnen Elementen sorgen. Du kannst eine CSS Resetsammlung wie [Normalize](http://necolas.github.io/normalize.css/), usw. benutzen, oder einen etwas einfacheren Ansatz wählen: + +```css +*, +*::before, +*::after { + box-sizing: border-box; + margin: 0; + padding: 0; +} +``` + +Nun werden Elemente von ihren Margins und Paddings befreit und `box-sizing` lässt dich das CSS Box-Modell handhaben. + +#### [Demo](http://codepen.io/AllThingsSmitty/pen/kkrkLL) + +**Hinweis:** Wenn du den [Inherit `box-sizing`](#inherit-box-sizing)-Tipp im unten folgenden Punkt befolgst, kannst du dich dafür entscheiden keine `box-sizing`-Eigenschaft in dein CSS Reset aufzunehmen. + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +### Übernehme `box-sizing` + +Übernehme `box-sizing` von `html`: + +```css +html { + box-sizing: border-box; +} + +*, +*::before, +*::after { + box-sizing: inherit; +} +``` + +Dies macht es einfacher das `box-sizing` über Plugins oder andere Komponenten zu verändern. + +#### [Demo](https://css-tricks.com/inheriting-box-sizing-probably-slightly-better-best-practice/) + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +### Benutze `unset`, anstatt alle Eigenschaften zurückzusetzen + +Wenn du die Eigenschaften eines Elements zurücksetzt, ist es nicht notwendig jede einzelne Eigenschaft individuell zurückzusetzen: + +```css +button { + background: none; + border: none; + color: inherit; + font: inherit; + outline: none; + padding: 0; +} +``` + +Du kannst alle Eigenschaften eines Elements spezifizieren, indem du das `all`-Kürzel verwendest. Der Wert `unset` setzt die Eigenschaften eines Elements auf den initialen Wert zurück: + +```css +button { + all: unset; +} +``` + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +### Benutze `:not()` um Rahmen an die Navigation zu setzen oder zu entfernen + +Anstatt den Rahmen zu ergänzen… + +```css +/* füge den Rahmen hinzu */ +.nav li { + border-right: 1px solid #666; +} +``` + +…um ihn dann beim letzten Element wieder zu entfernen… + +```css +/* entferne den Rahmen */ +.nav li:last-child { + border-right: none; +} +``` + +…benutze die `:not()`-Pseudoklasse um nur die Elemente zu gestalten, die du willst: + +```css +.nav li:not(:last-child) { + border-right: 1px solid #666; +} +``` + +Sicher, du kannst `.nav li + li` verwenden, aber mit `:not()` ist die Absicht sehr klar und der CSS Selektor definiert den Rahmen auf die Weise wie ihn auch ein Mensch beschreiben würde. + +#### [Demo](http://codepen.io/AllThingsSmitty/pen/LkymvO) + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +### Check If Font Is Installed Locally](#check-if-font-is-installed-locally) + +### Kontroller, om skrifttypen er installeret lokalt + +Du kan kontrollere, om en skrifttype er installeret lokalt, før du henter den eksternt, hvilket også er et godt ydelsestip. + +```css +@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; +} +``` + +Hat tip til Adam Argyle for at dele denne protip og [demoen](https://codepen.io/argyleink/pen/VwYJpgR). + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +### Ergänze `line-height` an `body` + +Du brauchst kein `line-height` an jedes `

`, ``, usw separat zu schreiben. Ergänze es stattdessen an `body`: + +```css +body { + line-height: 1.5; +} +``` + +Auf diese Weise können Textelemente dies einfach von `body` übernehmen. + +#### [Demo](http://codepen.io/AllThingsSmitty/pen/VjbdYd) + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +### Setze `:focus` für Form-Elemente + +Sehende Tastaturbenutzer_innen sind auf die Fokussierung angewiesen, um unterscheiden zu können wohin Tastaturevents auf der Seite gehen. Gestalte den Fokus für Formular-Elemente klar ersichtlich und konsistenter als die voreingestellte Browserimplementation: + +```css +a:focus, +button:focus, +input:focus, +select:focus, +textarea:focus { + box-shadow: none; + outline: #000 dotted 2px; + outline-offset: .05em; +} +``` + +#### [Demo](https://codepen.io/AllThingsSmitty/pen/ePzoOP/) + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +### Zentriere alles vertikal + +Nein, das ist keine Hexerei – du kannst wirklich alle Elemente vertikal zentrieren. +Das machst du mit Flexbox… + +```css +html, +body { + height: 100%; + margin: 0; +} + +body { + -webkit-align-items: center; + -ms-flex-align: center; + align-items: center; + display: -webkit-flex; + display: flex; +} +``` + +…und ebenso mit CSS Grid: + +```css +body { + display: grid; + height: 100vh; + margin: 0; + place-items: center center; +} +``` + +Möchtest du etwas anderes zentrieren? Vertikal, horizontal… alles, jederzeit, überall? CSS-Tricks hat [eine schöne Ausarbeitung](https://css-tricks.com/centering-css-complete-guide/) über all dies. + +#### [Demo](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +### Kommaseparierte Liste + +Lasse Listenpunkte wie eine echte kommaseparierte Liste aussehen: + +```css +ul > li:not(:last-child)::after { + content: ","; +} +``` + +Benutze die `:not()`-Pseudoklasse, um nach dem letzten Listenpunkt kein Komma anzuzeigen. + +**Hinweis:** Dieser Tipp mag hinsichtlich der Zugänglichkeit für Bildschirmvorleseprogramme nicht ideal sein. Auch Kopieren/Einfügen von browsergeneriertem Inhalt funktioniert nicht. Handle deswegen mit Vorsicht. + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +### Selektiere Items mit einem negativen `nth-child` + +Benutze ein negatives `nth-child` im CSS um Items von 1 bis n auszuwählen. + +```css +li { + display: none; +} + +/* wähle die Listenpunkte 1 bis 3 und zeige sie an */ +li:nth-child(-n+3) { + display: block; +} +``` + +Anderweitig, da du nun ein bisschen über die [Benutzung von `:not()`](#benutze-not-um-rahmen-an-die-navigation-zu-setzen-oder-zu-entfernen) gelernt hast, versuche folgendes: + +```css +/* wähle alle Listenpunkte außer die ersten 3 und zeige sie an */ +li:not(:nth-child(-n+3)) { + display: block; +} +``` + +#### [Demo](http://codepen.io/AllThingsSmitty/pen/WxjKZp) + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +### Benutze SVG für Symbole + +Es gibt keinen Grund SVG für Symbole nicht zu verwenden: + +```css +.logo { + background: url("logo.svg"); +} +``` + +SVG skaliert für alle verschiedenen Auflösungen sehr gut und wird von allen Browsern [zurück bis zu IE9](http://caniuse.com/#search=svg) unterstützt. Gebe deinen .png, .jpg, or .gif-jif-wasauchimmer-Dateien den Laufpass. + +**Hinweis:** Wenn du nur SVG-Symbole in Button-Schaltflächen für sehende Benutzer_innen verwendest und das SVG nicht geladen wird, kannst du die Zugänglichkeit wie folgt erhalten: + +```css +.no-svg .icon-only::after { + content: attr(aria-label); +} +``` + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +### Benutze den "lobotomisierte Eule"-Selektor + +Er hat zwar einen seltsamen Namen aber der Universal-Selektor (`*`) mit dem angrenzenden Geschwister-Selektor (`+`) kann starke CSS-Möglichkeiten darbieten: + +```css +* + * { + margin-top: 1.5em; +} +``` + +In diesem Beispiel bekommen alle Elemente im Fluss des Dokuments, die anderen Elementen folgen, `margin-top: 1.5em`. + +Für mehr bezüglich des "lobotomisierte Eule"-Selektors lese [Heydon Pickerings Eintrag](http://alistapart.com/article/axiomatic-css-and-lobotomized-owls) auf *A List Apart*. + +#### [Demo](http://codepen.io/AllThingsSmitty/pen/grRvWq) + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +### Benutze `max-height` für reine CSS-Galerien + +Implementiere reine CSS Galerien über `max-height` in Verbindung mit `overflow: hidden`: + +```css +.slider { + max-height: 200px; + overflow-y: hidden; + width: 300px; +} + +.slider:hover { + max-height: 600px; + overflow-y: scroll; +} +``` + +Das Element dehnt sich beim Überfahren zum Wert von `max-height` aus und die Galerie wird als das Ergebnis des Overflows dargestellt. + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +### Setze Tabellenzellen auf die gleiche Weite + +Tabellen können ein ganz schönes Problem sein. Versuche `table-layout: fixed`, um die Tabellenzellen auf die gleiche Größe zu setzen: + +```css +.calendar { + table-layout: fixed; +} +``` + +Schmerzfreie Tabellen-Layouts. + +#### [Demo](http://codepen.io/AllThingsSmitty/pen/jALALm) + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +### Benutze Flexbox, um von Margin-Hacks wegzukommen + +Wenn du mit Spaltenabständen arbeitest, kannst du dich von `nth-`, `first-` und `last-child`-Hacks verabschieden, indem du die Flexbox-Eigenschaft `space-between` verwendest: + +```css +.list { + display: flex; + justify-content: space-between; +} + +.list .person { + flex-basis: 23%; +} +``` + +Nun erscheinen Spaltenabstände immer gleichmäßig. + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +### Benutze den Attribut-Selektor mit leeren Verlinkungen + +Zeige Verlinkungen an, wenn das ``-Element keinen Textwert beinhaltet, das `href`-Attribut jedoch eine Verlinkung hat: + +```css +a[href^="http"]:empty::before { + content: attr(href); +} +``` + +Das ist äußerst praktisch. + +#### [Demo](http://codepen.io/AllThingsSmitty/pen/zBzXRx) + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +### Gestalte "Standard"-Verlinkungen + +Ergänze eine Darstellung für die von Browsern voreingestellte Verlinkung: + +```css +a[href]:not([class]) { + color: #008000; + text-decoration: underline; +} +``` + +Nun werden Verlinkungen, die über ein CMS eingesetzt wurden – welche überlicherweise kein `class`-Attribut haben – unterscheidbar sein, ohne die Kaskade im Allgemeinen zu beeinflussen. + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +### Boxen mit zugehörigem Größenverhältnis + +Um eine Box mit zugehörigem Größenverhältnis zu erstellen, brauchst du nur eine Padding-top/-bottom-Eigenschaft zu bezeichnen: + +```css +.container { + height: 0; + padding-bottom: 20%; + position: relative; +} + +.container div { + border: 2px dashed #ddd; + height: 100%; + left: 0; + position: absolute; + top: 0; + width: 100%; +} +``` + +Das Anwenden eines Wertes von 20% auf die Padding-Eigenschaft erzeugt eine Box mit der gleichen Höhe in Bezug auf 20% ihrer Breite. Ungeachtet der Weite des Ansichtsfensters, wird das Kind-Div sein Seitenverhältnis beibehalten (100% / 20% = 5:1). + +#### [Demo](http://codepen.io/AllThingsSmitty/pen/jALZvE) + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +### Gestalte defekte Bilder + +Erzeuge mit einem kleinen bisschen CSS ästhetisch ansprechendere defekte Bilder: + +```css +img { + display: block; + font-family: sans-serif; + font-weight: 300; + height: auto; + line-height: 2; + position: relative; + text-align: center; + width: 100%; +} +``` + +Nun ergänze Regeln für Pseudo-Elemente, die eine Nachricht für die Benutzer_innen darstellen, sowie eine URL-Referenz des defekten Bildes: + +```css +img::before { + content: "Entschuldige bitte, das Bild ist leider defekt :("; + display: block; + margin-bottom: 10px; +} + +img::after { + content: "(url: " attr(src) ")"; + display: block; + font-size: 12px; +} +``` + +Lerne mehr über das Gestalten dieses Modells in [Ire Aderinokun](https://github.com/ireade/)s [ursprünglichen Beitrag](http://bitsofco.de/styling-broken-images/). + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +### Benutze `rem` für globales Ändern der Größe; Benutze `em` für lokale Größenveränderungen + +Nachdem du die grundlegende Schriftgröße (`html { font-size: 100%; }`) festgelegt hast, setze die Schriftgrößen für Textelemente auf `em`: + +```css +h2 { + font-size: 2em; +} + +p { + font-size: 1em; +} +``` + +Dann setze die Schriftgröße für Module auf `rem`: + +```css +article { + font-size: 1.25rem; +} + +aside .module { + font-size: .9rem; +} +``` + +Nun sollte jedes Modul gegliedert, einfacher zu gestalten, wartbarer und flexibler sein. + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +### Verstecke automatisch abspielende Videos, die nicht auf stumm gesetzt sind + +Das ist ein großartiger Trick für ein speziell angefertigtes Stylesheet. Vermeide es die Benutzer_innen mit den Geräuschen eines automatisch startenden Videos zu überfordern. Zeige das Video nicht, wenn die Töne nicht auf stumm geschaltet sind: + +```css +video[autoplay]:not([muted]) { + display: none; +} +``` + +Erneut nutzen wir die [`:not()`](#benutze-not-um-rahmen-an-die-navigation-zu-setzen-oder-zu-entfernen)-Pseudoklasse zu unserem Vorteil. + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +### Benutze `:root` für flexible Schrift + +Die Größe der Schriftart innerhalb eines _responsive_ Layouts sollte mit jedem Ansichtsfenster veränderbar sein. Du kannst die Schriftgröße basierend auf der Höhe und Weite des Fensters berechnen, indem du `:root` verwendest: + +```css +:root { + font-size: calc(1vw + 1vh + .5vmin); +} +``` + +Nun kannst du die `root em`-Einheit verwenden, die auf den errechneten Werten von `:root` basiert: + +```css +body { + font: 1rem/1.6 sans-serif; +} +``` + +#### [Demo](http://codepen.io/AllThingsSmitty/pen/XKgOkR) + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +### Setze `font-size` auf Formular-Elemente für eine bessere mobile Erfahrung + +Um mobile Browser (iOS Safari, usw.) am Hereinzoomen in das HTML-Formular zu hindern sobald ein `` desplegable se toca, agrega `font-size` a la regla de selección: +Para evitar que los navegadores móviles (iOS Safari, _et al_.) hagan zoom sobre los elementos de un formulario HTML cuando un `` déroulante est taraudé, ajoutez `font-size` à la règle de sélection: +Pour éviter aux navigateurs mobiles (iOS Safari, _et al_.) de zoomer sur des éléments de formulaire HTML quand un menu déroulant `` αναπτυσόμενο μενού επιλεχθέι στην οθόνη, προσθέστο το `font-size` στον κανόνα του επιλέκτη: + +```css +input[type="text"], +input[type="number"], +select, +textarea { + font-size: 16px; +} +``` + +:dancer: + +[πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) + + +### Χρήση Γεγονότων Δείκτη για Έλεγχο Γεγονότων του Ποντικιού + + +[Γεγονότα ποντικού](https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events) σου επιτρέπουν να καθορίσεις πώς το ποντίκι αλληλεπιδρά με ένα στοιχείο που ακουμπάει. Για να απενεργοποιήσετε το προκαθορισμένο γεγονός ποντικιου πάνω σε ένα κουμπί, για παράδειγμα: + +```css +button:disabled { + opacity: .5; + pointer-events: none; +} +``` + +Είναι τόσο απλό. + +[πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) + + +### Ανάθεση `display: none` στο Τέλος των Γραμμών που Χρησιμοποιείται σαν Κενό + +Καθώς ο [Harry Roberts επισήμανε](https://twitter.com/csswizardry/status/1170835532584235008), αυτό μπορει να βοηθήσει τους CMS χρήστες να αποφύγουν την χρήση παραπάνω νέων γραμμών αντί για κένο : + +```css +br + br { + display: none; +} +``` + +[πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) + + +## Υποστήριξη + +Οι τωρινές εκδόσεις των Chrome, Firefox, Safari, καθώς και Edge. + +[πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) diff --git a/translations/gu-IND/README.md b/translations/gu-IND/README.md new file mode 100644 index 00000000..f1d37d96 --- /dev/null +++ b/translations/gu-IND/README.md @@ -0,0 +1,626 @@ +

+ light bulb icon +

+ +# CSS પ્રોપ્સ [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) + +તમારા CSS કુશળતાને ધ્યાનમાં રાખવામાં સહાય માટે ટિપ્સનો સંગ્રહ. + +> અન્ય મહાન યાદીઓ માટે તપાસો [@sindresorhus](https://github.com/sindresorhus/)'s ની યાદી [અદ્ભુત યાદીઓ](https://github.com/sindresorhus/awesome/). + + +## વિષયસુચીકોષ્ટક +અરજી / અનપ્પેલી કરવા માટે +* [પ્રોપ્સ](#પ્રોપ્સ) +* [આધાર](#આધાર) +* [ફાળો માર્ગદર્શિકા](../../CONTRIBUTING.md) + + +## પ્રોપ્સ + +1. [એક સીએસએસ રીસેટ વાપરો](#વાપરવ-a-css-રીસેટ) +1. [વારસો `box-sizing`](#વારસો-box-sizing)F +1. [બધા ગુણધર્મોને ફરીથી સેટ કરવાને બદલે 'અનસેટ' નો ઉપયોગ કરો](#બધા-ગુણધર્મોને-ફરીથી-સેટ-કરવાને-બદલે-અનસેટ-નો-ઉપયોગ-કરો) +1. [વાપરવ `:not()` અરજી / અનપ્પેલી કરવા માટે નેવિગેશન પર બોર્ડર્સ](#વાપરવ-not-અરજી--અનપ્પેલી-કરવા-માટે-નેવિગેશન-પર-બોર્ડર્સ) +1. [સ્થાનિક રીતે ફોન્ટ ઇન્સ્ટોલ કરેલું છે કે નહીં તે તપાસો](#સ્થાનિક-રીતે-ફોન્ટ-ઇન્સ્ટોલ-કરેલું-છે-કે-નહીં-તે-તપાસો) +1. [ઉમેરો `line-height` તરફ `body`](#ઉમેર-line-height-તરફ-body) +1. [ફોર્મ તત્વો માટે 'ધ્યાન કેન્દ્રિત કરો' સેટ કરો](#ફોર્મ-તત્વો-માટે-ધ્યાન-કેન્દ્રિત-કરો-સેટ-કરો) +1. [વર્ટિકલ-કેન્દ્ર કંઈપણ](#ઊભું-કેન્દ્ર-કંઈપણ) +1. [કોમા-વિભાજિત સૂચિ](#કોમા-વિભાજિત-સૂચિ) +1. [નકારાત્મક મદદથી વસ્તુઓ પસંદ કરો `nth-child`](#નકારાત્મક-મદદથી-વસ્તુઓ-પસંદ-કરો-nth-child) +1. [ચિહ્નો માટે SVG નો ઉપયોગ કરો](#વાપરવુ-માટે-svg-નો-ઉપયોગ-કરો) +1. [આ વાપરો "Lobotomized Owl" પસંદગીકાર](#આ-વાપરો-lobotomized-owl-પસંદગીકાર) +1. [વાપરવ `max-height` શુદ્ધ માટે CSS સ્લાઇડર્સનો](#વાપરવ-max-height-શુદ્ધ-માટે-css-સ્લાઇડર્સનો) +1. [સમાન-પહોળાઈ કોષ્ટક કોષ](#સમાન-પહોળાઈ-કોષ્ટક-કોષ) +1. [છુટકારો મેળવવા માર્જિન હેક્સ સાથે Flexbox](#છુટકારો-મેળવવા-માર્જિન-હેક્સ-સાથે-flexbox) +1. [વાપરવ એટ્રીબ્યુટ પસંદગીકારો સાથે ખાલી કડીઓ](#વાપરવ-એટ્રીબ્યુટ-પસંદગીકારો-સાથે-ખાલી-કડીઓ) +1. [પ્રકાર "Default" કડીઓ](#પ્રકાર-default-કડીઓ) +1. [આંતરિક ગુણોત્તર બૉક્સીસ](#આંતરિક-ગુણોત્તર-બૉક્સીસ) +1. [પ્રકાર તૂટેલી છબીઓ](#પ્રકાર-તૂટેલી-છબીઓ) +1. [વાપરવ `rem` માટે વૈશ્વિક કદ બદલવાનું; વાપરવ `em` માટે સ્થાનિક કદ બદલવાનું](#વાપરવ-rem-માટે-વૈશ્વિક-કદ-બદલવાનું-વાપરવ-em-માટે-સ્થાનિક-કદ-બદલવાનું) +1. [છુપાવો ઑટોપ્લે વિડિઓઝ તે નથ ચૂપ](#છુપાવો-ઑટોપ્લે-વિડિઓઝ-તે-નથ-ચૂપ) +1. [વાપરવ `:root` માટે Flexible Type](#વાપરવ-root-માટે-flexible-type) +1. [સેટ `font-size` on ફોર્મ તત્વો માટે a બેટર મોબાઇલ અનુભવ](#સેટ-font-size-on-ફોર્મ-તત્વો-માટે-a-બેટર-મોબાઇલ-અનુભવ) +1. [માઉસ ઇવેન્ટ્સ નિયંત્રણ કરવા માટે પોઇન્ટર ઇવેન્ટ્સનો ઉપયોગ કરો](#માઉસ-ઇવેન્ટ્સ-નિયંત્રણ-કરવા-માટે-પોઇન્ટર-ઇવેન્ટ્સનો-ઉપયોગ-કરો) +1. [અંતર `display: none` તરીકે વપરાયેલ લાઇન બ્રેક્સ પર સેટ કરો](#અંતર-display-none-તરીકે-વપરાયેલ-લાઇન-બ્રેક્સ-પર-સેટ-કરો) + + +### વાપરવ a CSS રીસેટ + +સીએસએસ રીસેટ્સ સ્ટાઇલ ઘટકો માટે સ્વચ્છ સ્લેટ સાથે વિવિધ બ્રાઉઝર્સમાં સ્ટાઇલ સુસંગતતાને અમલમાં મૂકવા માટે મદદ કરે છે. તમે જેમ કે CSS રીસેટ લાઇબ્રેરીનો ઉપયોગ કરી શકો છો [Normalize](http://necolas.github.io/normalize.css/), _et al._, અથવા તમે વધુ સરળ રીસેટ અભિગમનો ઉપયોગ કરી શકો છો: + +```css +*, +*::before, +*::after { + box-sizing: border-box; + margin: 0; + padding: 0; +} +``` + +હવે તત્વો માર્જિન અને પેડિંગની છીનવી લેવામાં આવશે, અને `box-sizing` તમે સીએસએસ બોક્સ મોડેલ સાથે લેઆઉટ મેનેજ કરી શકો છો. + +#### [પ્રદર્શન](http://codepen.io/AllThingsSmitty/pen/kkrkLL) + +**નોટ:** જો તમે અનુસરશો તો [Inherit `box-sizing`](#inherit-box-sizing) નીચે ટીપ તમે નીચેની શામેલ ન કરવાનું પસંદ કરી શકો છો `box-sizing` મિલકત માં તમારા CSS રીસેટ . + +[સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) + + +### વારસો `box-sizing` + +પરવાનગી આપો `box-sizing` માંથી વારસામાં આવશે `html`: + +```css +html { + box-sizing: border-box; +} + +*, +*::before, +*::after { + box-sizing: inherit; +} +``` + +આનાથી ફેરફાર કરવાનું સરળ બને છે `box-sizing` પ્લગઇન્સ અથવા અન્ય ઘટકોમાં લીવરેજ કે અન્ય વર્તન. + +#### [પ્રદર્શન](https://css-tricks.com/inheriting-box-sizing-probably-slightly-better-best-practice/) + +[સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) + + +### બધા ગુણધર્મોને ફરીથી સેટ કરવાને બદલે 'અનસેટ' નો ઉપયોગ કરો + +તત્વના ગુણધર્મોને ફરીથી સેટ કરતી વખતે, પ્રત્યેક વ્યક્તિગત સંપત્તિને ફરીથી સેટ કરવું જરૂરી નથી: + +```css +button { + background: none; + border: none; + color: inherit; + font: inherit; + outline: none; + padding: 0; +} +``` + +તમે 'બધા' લઘુલિપિનો ઉપયોગ કરીને એક તત્વની તમામ ગુણધર્મોને સ્પષ્ટ કરી શકો છો. `અનસેટ` માટે મૂલ્યને સેટ કરવાથી એક ઘટકના ગુણધર્મોને તેમની પ્રારંભિક મૂલ્યોમાં બદલાય છે: + +```css +button { + all: unset; +} +``` + +**નોંધ:** આઇ 11 માં `all` અને` અનસેટ` શોર્ટહેન્ડ સપોર્ટેડ નથી. + +[સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) + + +### વાપરવ `:not()` અરજી / અનપ્પેલી કરવા માટે નેવિગેશન પર બોર્ડર્સ + +તેના બદલે નો મૂકવા સરહદ પર... + +```css +/* add border */ +.nav li { + border-right: 1px solid #666; +} +``` + +...અને પછી તે છેલ્લા તત્વ બોલ લેવા... + +```css +/* remove border */ +.nav li:last-child { + border-right: none; +} +``` + +...વાપરવ `:not()` pseudo-class ફક્ત તમે ઇચ્છો તે તત્વો પર જ લાગુ કરો: + +```css +.nav li:not(:last-child) { + border-right: 1px solid #666; +} +``` + +CSS પસંદગીકાર સીમાને વ્યાખ્યાયિત કરે છે કે જે રીતે મનુષ્ય તેનું વર્ણન કરશે. + +#### [પ્રદર્શન](http://codepen.io/AllThingsSmitty/pen/LkymvO) + +[સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) + + +### સ્થાનિક રીતે ફોન્ટ ઇન્સ્ટોલ કરેલું છે કે નહીં તે તપાસો + +તમે તપાસ કરી શકો છો કે ફોન્ટ તેને દૂરસ્થ રીતે લાવવા પહેલાં સ્થાનિક રૂપે ઇન્સ્ટોલ કરેલું છે કે નહીં, તે પણ એક સારા પ્રદર્શનની મદદ છે. + +```css +@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; +} +``` + +આ પ્રોટીપ અને ડેમો શેર કરવા માટે એડમ આર્ગીલેને ટોપીની [મદદ](https://codepen.io/argyleink/pen/VwYJpgR). + +[સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) + + +### ઉમેર `line-height` તરફ `body` + +તમારે ઉમેરવાની જરૂર નથી `line-height` to દરેક `

`, ``, _et al_. અલગ. તેની જગ્યાએ, તેને ઉમેરવા `body`: + +```css +body { + line-height: 1.5; +} +``` + +આ માર્ગ textual તત્વો શકવું બોલાવે થી `body` સરળતાથી. + +#### [પ્રદર્શન](http://codepen.io/AllThingsSmitty/pen/VjbdYd) + +[સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) + + +### ફોર્મ તત્વો માટે 'ધ્યાન કેન્દ્રિત કરો' સેટ કરો + +દૃશ્યમાન કીબોર્ડ વપરાશકર્તાઓ પૃષ્ઠમાં કીબોર્ડ ઇવેન્ટ્સ ક્યાં જાય છે તે નિર્ધારિત કરવા પર ધ્યાન કેન્દ્રિત કરે છે. ફોર્મ ઘટકો માટે ધ્યાન કેન્દ્રિત કરો અને બ્રાઉઝરનું ડિફૉલ્ટ અમલીકરણ પછી સુસંગત રહો: + +```css +a:focus, +button:focus, +input:focus, +select:focus, +textarea:focus { + box-shadow: none; + outline: #000 dotted 2px; + outline-offset: .05em; +} +``` + +#### [Demo](https://codepen.io/AllThingsSmitty/pen/ePzoOP/) + +[સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) + + +### ઊભું કેન્દ્ર કંઈપણ + +ના, તે કાળા જાદુ નથી, તમે ખરેખર ઊભી તત્વોને કેન્દ્રિત કરી શકો છો: + +```css +html, +body { + height: 100%; + margin: 0; +} + +body { + -webkit-align-items: center; + -ms-flex-align: center; + align-items: center; + display: -webkit-flex; + display: flex; +} +`` +...અને CSS ગ્રીડ સાથે પણ: + +```css +body { + display: grid; + height: 100vh; + margin: 0; + place-items: center center; +} +```` + +કેન્દ્ર માંગો છો કંઈક બીજું? વર્ટિકલ, આડા...કંઈપણ, કોઈપણ સમયે, ગમે ત્યાં? CSS-Tricks has [a nice write-up](https://css-tricks.com/centering-css-complete-guide/) on કરવાનું બધા કે. + +#### [પ્રદર્શન](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) + +[સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) + + +### કોમા-વિભાજિત સૂચિ + +સૂચિ આઇટમ્સ વાસ્તવિક, અલ્પવિરામથી વિભાજીત સૂચિની જેમ દેખાય છે તે બનાવો: + +```css +ul > li:not(:last-child)::after { + content: ","; +} +``` + +વાપરવ આ `:not()` pseudo-class તેથી છેલ્લી વસ્તુમાં કોઈ અલ્પવિરામ ઉમેરવામાં આવી નથી. + +**નોટ:** આ ટિપ સુલભતા માટે આદર્શ નથી, ખાસ કરીને સ્ક્રીન વાચકો. અને બ્રાઉઝરમાંથી કૉપિ / પેસ્ટ CSS- જનરેટેડ સામગ્રી સાથે કામ કરતું નથી. સાવધાની સાથે આગળ વધો. + +[સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) + + +### નકારાત્મક મદદથી વસ્તુઓ પસંદ કરો `nth-child` + +વાપરવ નકારાત્મક `nth-child` વસ્તુઓ પસંદ કરવા માટે CSS માં 1 દ્વારા n. + +```css +li { + display: none; +} + +/* select items 1 through 3 and display them */ +li:nth-child(-n+3) { + display: block; +} +``` + +અથવા, કારણ કે તમે પહેલેથી જ વિશે થોડું શીખ્યા છે [using `:not()`](#use-not-to-applyunapply-borders-on-navigation), પ્રયત્ન કરો: + +```css +/* select all items except the first 3 and display them */ +li:not(:nth-child(-n+3)) { + display: none; +} +``` + +વેલ તે ખૂબ સરળ હતું. + +#### [પ્રદર્શન](http://codepen.io/AllThingsSmitty/pen/WxjKZp) + +[સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) + + +### વાપરવુ માટે SVG નો ઉપયોગ કરો + +ચિહ્નો માટે એસવીજીનો ઉપયોગ ન કરવા માટે કોઈ કારણ નથી + +```css +.logo { + background: url("logo.svg"); +} +``` + +The SVG scale is good for all resolution types and it is supported in all browsers [back to IE9](http://caniuse.com/#search=svg). તેથી છુટકારો મેળવવા .png, .jpg, or .gif-jif-whatev ફાઈલો. + +**નોટ:** જો તમારી પાસે SVG આઇકોન-માત્ર બટનો છે અને જોવામાં આવેલાં વપરાશકર્તાઓ માટે SVG લોડ કરવામાં નિષ્ફળ જાય, તો તે એક્સેસીબિલીટી જાળવી રાખવામાં મદદ કરશે.: + +```css +.no-svg .icon-only::after { + content: attr(aria-label); +} +``` + +[સામગ્રીઓના કોષ્ટકમાં પાછ](#કોષ્ટક-સામગ્રીઓ) + + +### આ વાપરો "Lobotomized Owl" પસંદગીકાર + +તેમાં વિચિત્ર નામ હોઈ શકે છે પરંતુ સાર્વત્રિક પસંદગીકારનો ઉપયોગ કરી શકો છો (`*`) અડીન બહેન સિલેક્ટર સાથે (`+`) શક્તિશાળી CSS ક્ષમતા પ્રદાન કરી શકે છે: + +```css +* + * { + margin-top: 1.5em; +} +``` + +આ ઉદાહરણમાં, અન્ય ઘટકોને અનુસરતા દસ્તાવેજના પ્રવાહમાંના બધા તત્વો પ્રાપ્ત થશે `margin-top: 1.5em`. + +વધુ માટે "lobotomized owl" પસંદગીકાર, વાંચવું [Heydon Pickering's post](http://alistapart.com/article/axiomatic-css-and-lobotomized-owls) on *A List Apart*. + +#### [પ્રદર્શન](http://codepen.io/AllThingsSmitty/pen/grRvWq) + +[સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) + + +### વાપરવ `max-height` શુદ્ધ માટે CSS સ્લાઇડર્સન + +ફક્ત ઉપયોગ કરીને CSS- ફક્ત સ્લાઇડર્સનો અમલ કરો `max-height` ઓવરફ્લો છુપાયેલ સાથે: + +```css +.slider { + max-height: 200px; + overflow-y: hidden; + width: 300px; +} + +.slider:hover { + max-height: 600px; + overflow-y: scroll; +} +``` + +આ તત્વ વિસ્તરે છે `max-height` Value on hover and slider display as a result of overflow. + +[સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) + + +### સમાન-પહોળાઈ કોષ્ટક કોષ + +કોષ્ટકો સાથે કામ કરવા માટે પીડા હોઈ શકે છે જેથી આનો ઉપયોગ કરીને પ્રયાસ કરો `table-layout: fixed` કોષો સમાન પહોળાઈ પર રાખો: + +```css +.calendar { + table-layout: fixed; +} +``` + +પેઇન-મુક્ત કોષ્ટક લેઆઉટ. + +#### [પ્રદર્શન](http://codepen.io/AllThingsSmitty/pen/jALALm) + +[સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) + + +### છુટકારો મેળવવા માર્જિન હેક્સ સાથે Flexbox + +સ્તંભ ગટર સાથે કામ કરતી વખતે તમે છુટકારો મેળવી શકો છો `nth-`, `first-`, અને `last-child` હેક્સ દ્વારા ઉપયોગ કરીને flexbox's `space-between` મિલકત: + +```css +.list { + display: flex; + justify-content: space-between; +} + +.list .person { + flex-basis: 23%; +} +``` + +હવે સ્તંભ ગટર હંમેશા સરખે ભાગે-અંતરે દેખાય છે. + +[સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) + + +### વાપરવ એટ્રીબ્યુટ પસંદગીકારો સાથે ખાલી કડીઓ + +લિંક્સ દર્શાવો જ્યારે `` તત્વ કોઈ લખાણ કિંમત નથી પરંતુ `href` લક્ષણ એક લિંક છે: + +```css +a[href^="http"]:empty::before { + content: attr(href); +} +``` + +તે ખૂબ અનુકૂળ છે + +#### [પ્રદર્શન](http://codepen.io/AllThingsSmitty/pen/zBzXRx) + +[સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) + + +### પ્રકાર "Default" કડીઓ + +માટે એક શૈલી ઉમેરો "default" લિંક્સ: + +```css +a[href]:not([class]) { + color: #008000; + text-decoration: underline; +} +``` + +હવે લિંક્સ કે જે CMS દ્વારા દાખલ કરવામાં આવે છે, જે સામાન્ય રીતે એક નથી `class` એટ્રિબ્યુટ, સામાન્ય રીતે કાસ્કેડને અસર કરતા વગર ભેદ રાખશે. + +[સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) + + +### આંતરિક ગુણોત્તર બૉક્સીસ + +સ્વભાવિક રેશિયો સાથે બૉક્સ બનાવવા માટે, તમારે ફક્ત ટોચ અથવા તળિયે ગાદીને DIV પર લાગુ કરવાની જરૂર છે: + +```css +.container { + height: 0; + padding-bottom: 20%; + position: relative; +} + +.container div { + border: 2px dashed #ddd; + height: 100%; + left: 0; + position: absolute; + top: 0; + width: 100%; +} +``` + +પેડિંગ માટે 20% નો ઉપયોગ કરીને તેના પહોળાઈના 20% જેટલા બૉક્સની ઊંચાઇને બનાવે છે. કોઈ વ્યૂપોર્ટની પહોળાઇ, બાળક ડિવ તેના પાસા રેશિયો રાખશે (100% / 20% = 5:1). + +#### [પ્રદર્શન](http://codepen.io/AllThingsSmitty/pen/jALZvE) + +[સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) + + +### પ્રકાર તૂટેલી છબીઓ + +તૂટેલી તસવીરો CSS ના થોડુંક સાથે વધુ સૌંદર્યલક્ષી-આનંદી બનાવો: + +```css +img { + display: block; + font-family: sans-serif; + font-weight: 300; + height: auto; + line-height: 2; + position: relative; + text-align: center; + width: 100%; +} +``` + +હવે ઉમેરો pseudo-elements તૂટેલી છબીના વપરાશકર્તા સંદેશ અને URL સંદર્ભને પ્રદર્શિત કરવાના નિયમો: + +```css +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; +} +``` + +આ પેટર્ન માટે સ્ટાઇલ વિશે વધુ જાણો [Ire Aderinokun](https://github.com/ireade/)'s [original post](http://bitsofco.de/styling-broken-images/). + +[સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) + + +### વાપરવ `rem` માટે વૈશ્વિક કદ બદલવાનું; વાપરવ `em` માટે સ્થાનિક કદ બદલવાનું + +રુટ પર મૂળ ફોન્ટ માપ સુયોજિત કર્યા પછી (`html { font-size: 100%; }`), શાબ્દિક તત્વો માટે ફૉન્ટનું કદ સેટ કરો `em`: + +```css +h2 { + font-size: 2em; +} + +p { + font-size: 1em; +} +``` + +પછી મોડ્યુલો માટે ફૉન્ટ-કદ સેટ કરો to `rem`: + +```css +article { + font-size: 1.25rem; +} + +aside .module { + font-size: .9rem; +} +``` + +હવે દરેક મોડ્યુલ શ્રેણીબદ્ધ અને સરળ, વધુ નિભાવવા યોગ્ય અને લવચીક બની જાય છે. + +[સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) + + +### છુપાવો ઑટોપ્લે વિડિઓઝ તે નથ ચૂપ + +આ વૈવિધ્યપૂર્ણ વપરાશકર્તા સ્ટાઇલશીટ માટે એક મહાન યુક્તિ છે. એક વપરાશકર્તા દ્વારા અવાજ સાથે ઓવરલોડિંગ કરવાનું ટાળો, જે જ્યારે પૃષ્ઠ લોડ થાય ત્યારે ઑટોપ્લે કરે છે. જો અવાજ મૌન નથી, તો વિડિઓ બતાવશો નહીં: + +```css +video[autoplay]:not([muted]) { + display: none; +} +``` + +ફરી એક વાર, અમે આનો ઉપયોગ કરીને લાભ લઈ રહ્યાં છીએ [`:not()`](#use-not-to-applyunapply-borders-on-navigation) pseudo-class. + +[સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) + + +### વાપરવ `:root` માટે Flexible Type + +એક પ્રતિસાદિત લેઆઉટમાં ટાઇપ ફૉન્ટનું કદ દરેક વ્યૂપોર્ટ સાથે વ્યવસ્થિત થવું જોઈએ. તમે ઉપયોગ કરીને વ્યૂપોર્ટની ઊંચાઈ અને પહોળાઈના આધારે ફોન્ટ કદની ગણતરી કરી શકો છો `:root`: + +```css +:root { + font-size: calc(1vw + 1vh + .5vmin); +} +``` + +હવે તમે આ ઉપયોગ શ `root em` દ્વારા ગણવામાં આવેલ કિંમત પર આધારિત એકમ `:root`: + +```css +body { + font: 1rem/1.6 sans-serif; +} +``` + +#### [પ્રદર્શન](http://codepen.io/AllThingsSmitty/pen/XKgOkR) + +[સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) + + +### સેટ `font-size` on ફોર્મ તત્વો માટે a બેટર મોબાઇલ અનુભવ + +મોબાઇલ બ્રાઉઝર્સને ટાળવા માટે (iOS Safari, _et al_.) થી ઝુમિંગ HTML ફોર્મ એલિમેન્ટ્સ પર જ્યારે એક ``, aggiungi `font-size` alle regole del selettore: + +```css +input[type="text"], +input[type="number"], +select, +textarea { + font-size: 16px; +} +``` + +:dancer: + +[torna al sommario](#sommario) + + +### Utilizzare gli eventi puntatore per controllare gli eventi del mouse + +[Eventi puntatore](https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events) consentono di specificare come il mouse interagisce con l'elemento che sta toccando. Per disabilitare l'evento puntatore predefinito su un pulsante, ad esempio: + +```css +button:disabled { + opacity: .5; + pointer-events: none; +} +``` + +È così semplice. + +[torna al sommario](#sommario) + + +### Imposta `display: none` su Line Breaks usati come Spaziatura + +Come [Harry Roberts ha sottolineato](https://twitter.com/csswizardry/status/1170835532584235008), questo può aiutare a impedire agli utenti CMS di utilizzare interruzioni di riga aggiuntive per la spaziatura: + +```css +br + br { + display: none; +} +``` + +[torna al sommario](#sommario) + + +## Supporto + +Le attuali versioni di Chrome, Firefox, Safari, ed Edge. \ No newline at end of file diff --git a/translations/ja-JP/README.md b/translations/ja-JP/README.md new file mode 100644 index 00000000..2ad307d9 --- /dev/null +++ b/translations/ja-JP/README.md @@ -0,0 +1,681 @@ +

+ light bulb icon +

+ +# CSSの便利な小技・テクニックのまとめ [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) + +CSSのプロのスキルになるようにアドバイスのリストを紹介します。 + +> 他のリストのため: [Awesome リスト](https://github.com/sindresorhus/awesome/) の [@sindresorhus](https://github.com/sindresorhus/) をチェックSしてください。. + + +
+ +## 目次 + +* [プロチップス](#protips) +* [サポート](#soutien) +* [参考](#references) +* [コントリビュート](../../CONTRIBUTING.md) + + +
+ +## プロチップス + +1. [CSSのリセットを使用します](#use-a-css-reset) +1. [box-sizingをコンポーネントごとに変更](#inherit-box-sizing) +1. [すべてのプロパティをリセットする代わりに `unset`を使う](#use-unset-instead-of-resetting-all-properties) +1. [`:not()` を使用 / ボーダーを削除](#use-not-to-applyunapply-borders-on-navigation) +1. [フォントがローカルにインストールされているかどうかを確認します](#check-if-font-is-installed-locally) +1. [`body`に`line-height`を加える](#add-line-height-to-body) +1. [フォーム要素に `:focus`を設定する](#set-focus-for-form-elements) +1. [天地の中央に配置](#vertically-center-anything) +1. [リストをカンマ区切りにする](#comma-separated-lists) +1. [ネガティブな「:nth-child」を使用してアイテムを選択](#select-items-using-negative-nth-child) +1. [SVGのアイコン](#use-svg-for-icons) +1. [Owlを使用](#use-the-lobotomized-owl-selector) +1. [CSSで実装されたスライダーにはmax-heightを使う](#use-max-height-for-pure-css-sliders) +1. [テーブルのセルの幅を均等にする](#equal-width-table-cells) +1. [Flexboxのマージンハックを取り除く](#get-rid-of-margin-hacks-with-flexbox) +1. [リンクにテキストが無い時はURLを表示](#use-attribute-selectors-with-empty-links) +1. [デフォルトのリンクをスタイル](#style-default-links) +1. [内在比率のボックス](#intrinsic-ratio-boxes) +1. [リンク切れの画像要素をスタイル](#style-broken-images) +1. [グローバルのサイズ指定に「rem」、ローカルに「em」を使用](#use-rem-for-global-sizing-use-em-for-local-sizing) +1. [動画の自動再生を隠す](#hide-autoplay-videos-that-arent-muted) +1. [フレクシブルタイプの`:root`を使用](#use-root-for-flexible-type) +1. [スマホ向け、フォーム要素のフォントサイズの設定](#set-font-size-on-form-elements-for-a-better-mobile-experience) +1. [ポインターイベントを使用してマウスイベントを制御する](#use-pointer-events-to-control-mouse-events) +1. [間隔として使用される改行に「display:none」を設定します](#set-display-none-on-line-breaks-being-used-as-spacing) + + +
+ +### CSSのリセットを使用します + +CSSのリセットはスタイリング要素のための白紙の状態で異なるブラウザ間でスタイルの一貫性を強化するのに役立ちます。あなたは[Normalize](http://necolas.github.io/normalize.css/)、_et al._のようにCSSのリセットライブラリを使用するか、より簡略化リセットアプローチを使用することができます。 + +```css +*, +*::before, +*::after { + box-sizing: border-box; + margin: 0; + padding: 0; +} +``` + +今の要素は、マージンやパディングを剥奪し、`box-sizing`は、CSSボックスモデルとレイアウトを管理することができますされます。 + +#### [デモ](http://codepen.io/AllThingsSmitty/pen/kkrkLL) + +**注意:**あなたがあなたのCSSのリセットで[Inherit `box-sizing`](#inherit-box-sizing) プロパティが含まれていないことを選択する可能性があります下に`box-sizing`ヒントに従っている場合。 + + +[目次へ戻る](#table-of-contents) + + +
+ +### `box-sizing`をコンポーネントごとに変更 + +`box-sizing`はhtml要素で指定し、継承して利用すると、コンポーネントで変える時に簡単です。 + +```css +html { + box-sizing: border-box; +} + +*, +*::before, +*::after { + box-sizing: inherit; +} + +``` + +これでプラグインかその他のコンポーネントに `box-sizing` を変更しやすくなります。 + +#### [デモ](https://css-tricks.com/inheriting-box-sizing-probably-slightly-better-best-practice/) + +[目次へ戻る](#table-of-contents) + + +
+ +### すべてのプロパティをリセットする代わりに `unset`を使う + +要素のプロパティをリセットするときは、個々のプロパティをリセットする必要はありません。 + +```css +button { + background: none; + border: none; + color: inherit; + font: inherit; + outline: none; + padding: 0; +} +``` + +要素のプロパティのすべてを `all`省略形で指定することができます。 値を `unset`に設定すると、要素のプロパティが初期値に変更されます: + +```css +button { + all: unset; +} +``` + +[目次へ戻る](#table-of-contents) + + +
+ +### `:not()`を使用して、リスト要素で実装したナビゲーションの最後のアイテムだけに区切り線を削除します。 + +ボーダーを書いて。。。 + +```css +/* add border */ +.nav li { + border-right: 1px solid #666; +} +``` + +ラストチャイルドで非表示するより + +```css +/* remove border */ +.nav li:last-child { + border-right: none; +} +``` + +`:not()`を使用するとシンプルなコードで指定できます。 + +```css +.nav li:not(:last-child) { + border-right: 1px solid #666; +} +``` + +CSSセレクターは、境界線を人間が表現する方法で定義します。 + +#### [デモ](http://codepen.io/AllThingsSmitty/pen/LkymvO) + +[目次へ戻る](#table-of-contents) + + +
+ +### フォントがローカルにインストールされているかどうかを確認します + +フォントをリモートでフェッチする前に、フォントがローカルにインストールされているかどうかを確認できます。これもパフォーマンスのヒントになります。 + +```css +@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; +} +``` + +このプロチップと[デモ](https://codepen.io/argyleink/pen/VwYJpgR)を共有してくれたAdam Argyleへの帽子のヒント. + +[目次へ戻る](#table-of-contents) + + +
+ +### `body` に`line-height`を加える + +`body`要素で`line-height`を指定することで`p`, `h*`などにその値が継承されるため、それぞれに`line-height`を指定する必要がなくなります。 + +```css +body { +  line-height: 1.5; +} +``` + +#### [デモ](http://codepen.io/AllThingsSmitty/pen/VjbdYd) + +[目次へ戻る](#table-of-contents) + + +
+ +### フォーム要素に `:focus`を設定する + +視認されたキーボードユーザーは、キーボードイベントがページ内のどこに移動するかを決定するためにフォーカスを当てています。 フォーム要素のフォーカスを目立たせ、ブラウザのデフォルトの実装と一貫性を持たせる: + +```css +a:focus, +button:focus, +input:focus, +select:focus, +textarea:focus { + box-shadow: none; + outline: #000 dotted 2px; + outline-offset: .05em; +} +``` + +#### [デモ](https://codepen.io/AllThingsSmitty/pen/ePzoOP/) + +[目次へ戻る](#table-of-contents) + + +
+ +### 天地の中央に配置 + +なんでも天地の中央に配置できます!! + +```css +html, +body { + height: 100%; + margin: 0; +} + +body { + -webkit-align-items: center; + -ms-flex-align: center; + align-items: center; + display: -webkit-flex; + display: flex; +} +``` + +...CSSグリッド: + +```css +body { + display: grid; + height: 100vh; + margin: 0; + place-items: center center; +} +``` + +なんでも中央に揃いたいですか? CSS-Tricks の[セントリングガイド](https://css-tricks.com/centering-css-complete-guide/) をチェックしてください。 + +#### [デモ](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) + +[目次へ戻る](#table-of-contents) + + +
+ +### リストをカンマ区切りにする + +リストの各アイテムをカンマ区切りにします。 + +```css +ul > li:not(:last-child)::after { + content: ","; +} +``` + +`:not()` を使えば最後のエレメントにカンマ追加されないようにします。 + +**備考:** アクセシビリティによくないので気をつけてをお使いください。 + +[目次へ戻る](#table-of-contents) + + +
+ +### ネガティブな `:nth-child` を使用してアイテムを選択 + +`nth-child`にはネガティブな値も指定できます。 + +```css +li { + display: none; +} + +/* select items 1 through 3 and display them */ +li:nth-child(-n+3) { + display: block; +} +``` + +また [`:not()`](#use-not-to-applyunapply-borders-on-navigation) を使用してこちらをのコードを書いてみてください: + +```css +/* select all items except the first 3 and display them */ +li:not(:nth-child(-n+3)) { + display: none; +} +``` + +簡単でしょう〜! + +#### [デモ](http://codepen.io/AllThingsSmitty/pen/WxjKZp) + +[目次へ戻る](#table-of-contents) + + +
+ +### SVGのアイコン + +アイコンとしてSVGを使えない理由がないです! + +```css +.logo { +  background: url("logo.svg"); +} +``` + +SVGは [IE9](http://caniuse.com/#search=svg)以降のすべてのブラウザでサポートされています。 + +**備考:** ボタンがSVGだけで作られている場合、SVGがローディングされなかったらアクセシビリティのためこちらのコードを書いて見てください: + +```css +.no-svg .icon-only::after { + content: attr(aria-label); +} +``` + +[目次へ戻る](#table-of-contents) + + +
+ +### Owlを使用 + +変な名前ですが(`*`) と (`+`) を使用するとパワフルCSSセレクターになります! + +```css +* + * { +  margin-top: 1.5em; +} +``` + +全てのページの要素にある要素が`margin-top: 1.5em`をもらいます。 + +Owlについて詳しくはこちら:*List Apart* の[ヘイドンピケリングの記事](http://alistapart.com/article/axiomatic-css-and-lobotomized-owls) + +#### [デモ](http://codepen.io/AllThingsSmitty/pen/XKgOkR) + +[目次へ戻る](#table-of-contents) + + +
+ +### CSSで実装されたスライダーには`max-height`を使う + +CSSで実装されたスライダーは、`max-height`を`overflow: hidden;`と一緒に使ってください。 + +```css +.slider { + max-height: 200px; + overflow-y: hidden; + width: 300px; +} + +.slider:hover { + max-height: 600px; + overflow-y: scroll; +} +``` + +ホバーの時`max-height`の要素を拡張オバーフローの結果でスライダーが表示されます。 + +[目次へ戻る](#table-of-contents) + + +
+ +### テーブルのセルの幅を均等にする + +テーブルの各セルの幅を均等にするには、`table-layout: fixed;`を使うと簡単にできます。 + +```css +.calendar { +  table-layout: fixed; +} +``` + +簡単にテーブルレイアウトを作れます。 + +#### [デモ](http://codepen.io/AllThingsSmitty/pen/jALALm) + +[目次へ戻る](#table-of-contents) + + +
+ +### Flexboxのマージンハックを取り除く + +`flexbox`でカラムの溝をつくる時、`nth-`, `first-`, `last-child`などのハックで最後の溝を取り除くことができますが、それは`flexbox`の`space-between`プロパティを使うだけで解決します。 + + +```css +.list { + display: flex; + justify-content: space-between; +} + +.list .person { + flex-basis: 23%; +} +``` + +columnのスペースが揃えている。 + +[目次へ戻る](#table-of-contents) + + + + +### リンクにテキストが無い時はURLを表示 + +リンクの`href`属性にはURLがあり、リンクのテキストがない場合に、下記のCSSを使用すると、リンク先のURLを表示します。 + +```css +a[href^="http"]:empty::before { + content: attr(href); +} +``` + +便利ですよー! + +#### [デモ](http://codepen.io/AllThingsSmitty/pen/zBzXRx) + +[目次へ戻る](#table-of-contents) + + + + +### `:not`を使ってデフォルトのリンクをスタイル + +デフォルトのリンクのスタイルを追加: + +```css +a[href]:not([class]) { + color: #008000; + text-decoration: underline; +} +``` + +CMSで挿入される通常class属性を持たないリンクに`:not`を使ってスタイルを定義します。 + +[目次へ戻る](#table-of-contents) + + +
+ +### 内在比率のボックス + +ボックスを内在比率で作成するには、ボックスの上部か下部に`div`の詰め物を適用します。 + +```css +.container { + height: 0; + padding-bottom: 20%; + position: relative; +} + +.container div { + border: 2px dashed #ddd; + height: 100%; + left: 0; + position: absolute; + top: 0; + width: 100%; +} +``` + +paddingに20%を使っているのは、そのボックスの高さを幅の20%と等しくします。ビューポートの幅に関わらず、子のdiv要素のアスペクト比は「100%:20%(5:1)」を保持します。 + +#### [デモ](http://codepen.io/AllThingsSmitty/pen/jALZvE) + +[目次へ戻る](#table-of-contents) + + +
+ +### リンク切れの画像要素をスタイル + +よりよいユーザエクスペリエンスを提供するために、リンク切れの画像要素にスタイルを定義します。もちろんリンク切れがないのがベストですが、絶対に存在しない訳ではありません。 + +```css +img { + display: block; + font-family: sans-serif; + font-weight: 300; + height: auto; + line-height: 2; + position: relative; + text-align: center; + width: 100%; +} +``` + +疑似要素を使い、ユーザーの役に立つ情報を加えることもできます。 + +```css +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; +} +``` + +このようなスタイリングに興味があればこちらに参考してください:[イレ アデリノクン](https://github.com/ireade/)' [リンク切れの画像についての記事](http://bitsofco.de/styling-broken-images/). + +[目次へ戻る](#table-of-contents) + + +
+ +### グローバルのサイズ指定に`rem`、ローカルに`em`を使用 + +ベースのフォントサイズを`html{font-size: 16px;}`にルート指定し、テキスト要素を`em`で指定します。 + +```css +h2 { +  font-size: 2em; +} + +p { +  font-size: 1em; +} +``` + +モジュールのフォントサイズは`rem`で指定します。 + +```css +article { + font-size: 1.25rem; +} + +aside .module { + font-size: .9rem; +} +``` + +モジュールごとに分けるとスタイルするのが簡単で、メンテナンス性もアップします。 + +[目次へ戻る](#table-of-contents) + + +
+ +### 動画の自動再生を隠す + +これはカスタマイズされたユーザースタイルシートのための素晴らしいテクニックです。ページがロードされた時、動画が自動再生されて音がでてしまうユーザーの負担を軽減します。もし無音にできないなら、動画を使わないでください。 + +```css +video[autoplay]:not([muted]) { + display: none; +} +``` + +こちらも [`:not()`](#use-not-to-applyunapply-borders-on-navigation)を使用できます! + +[目次へ戻る](#table-of-contents) + + +
+ +### フレクシブルタイプの`:root`を使用 + +レスポンシブ対応時に、フォントのサイズをビューポートごとに適応することができます。`:root`を使い、ビューポートの高さと幅に基づいてフォントのサイズを定義することができます。 + +```css +:root { + font-size: calc(1vw + 1vh + .5vmin); +} +``` + +#### [デモ](http://codepen.io/AllThingsSmitty/pen/XKgOkR) + +`:root`で定義した値に基づいて、それぞれのタグや要素に`em`を使って利用します。 + +```css +body { + font: 1rem/1.6 sans-serif; +} +``` + +[目次へ戻る](#table-of-contents) + + +
+ +### スマホ向け、フォーム要素のフォントサイズの設定 + +スマホでセレクト要素のドロップダウンをタップした時に、iOS Safariでフォーム要素にズームインするのを回避するために、フォントサイズを加えます。 + +```css +input[type="text"], +input[type="number"], +select, +textarea { + font-size: 16px; +} +``` + +:dancer: + +[目次へ戻る](#table-of-contents) + + +
+ +### ポインターイベントを使用してマウスイベントを制御する + +[Pointer events](https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events)では、マウスがタッチしている要素とどのように対話するかを指定することができます。 ボタン上のデフォルトポインタイベントを無効にするには、次のようにします。 + +```css +button:disabled { + opacity: .5; + pointer-events: none; +} +``` + +それは簡単です。 + +[目次へ戻る](#table-of-contents) + + +
+ +### 間隔として使用される改行に `display:none` を設定します + +[ハリー・ロバーツが指摘したように](https://twitter.com/csswizardry/status/1170835532584235008)、これはCMSユーザーがスペースのために余分な改行を使用するのを防ぐのに役立ちます: + +```css +br + br { + display: none; +} +``` + +[目次へ戻る](#table-of-contents) + + +
+ +## サポート + +現在のChrome, Firefox, Safari, のバージョンとEdge. diff --git a/translations/ko-KR/readme.md b/translations/ko-KR/readme.md new file mode 100644 index 00000000..2cd47c2d --- /dev/null +++ b/translations/ko-KR/readme.md @@ -0,0 +1,672 @@ +

+ light bulb icon +

+ +# CSS 프로팁 [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) + +CSS스킬을 프로처럼 만들어주는 팁 모음 + +> 또 다른  꼭 확인해 볼 만한 [@sindresorhus](https://github.com/sindresorhus/)의 큐레이트 리스트  [awesome lists](https://github.com/sindresorhus/awesome/). + +
+ +## 목차 + +* [프로팁](#프로팁) +* [지원](#지원) +* [컨트리뷰션 가이드라인](../../CONTRIBUTING.md) + + +
+ +## 프로팁 + +1. [CSS Reset을 사용](#use-a-css-reset) +1. [`box-sizing`을 컴포넌트마다 변경](#inherit-box-sizing) +1. [모든 프로퍼티를 리셋하는 대신에 `unset`를 쓴다](#use-unset-instead-of-resetting-all-properties) +1. [`:not()` 를 사용하여 보더를 삭제](#use-not-to-applyunapply-borders-on-navigation) +1. [글꼴이 로컬로 설치되어 있는지 확인](#check-if-font-is-installed-locally) +1. [`body`에 `line-height` 넣기](#add-line-height-to-body) +1. [폼 요소에`: focus`를 설정하기](#set-focus-for-form-elements) +1. [전부 수직 정렬 만들기](#vertically-center-anything) +1. [리스트를 콤마로 나누기](#comma-separated-lists) +1. [Negative `nth-child`를 사용하여 아이템 나누기](#select-items-using-negative-nth-child) +1. [SVG를 아이콘으로 사용하기](#use-svg-for-icons) +1. ["Lobotomized Owl" Selector 사용하기](#use-the-lobotomized-owl-selector) +1. [CSS로 구현된 슬라이더에 `max-height` 사용하기](#use-max-height-for-pure-css-sliders) +1. [테이블 셀의 너비 균등하게 하기](#equal-width-table-cells) +1. [Flexbox의 Margin Hack 제거](#get-rid-of-margin-hacks-with-flexbox) +1. [링크에 텍스트가 없을 때의 url 표시](#use-attribute-selectors-with-empty-links) +1. ["Default" 링크 스타일](#style-default-links) +1. [내재 비율의 박스](#intrinsic-ratio-boxes) +1. [깨진 링크의 이미지 스타일](#style-broken-images) +1. [글로벌 사이즈 지정에 `rem`; 로컬  사이즈 지정에 `em`](#use-rem-for-global-sizing-use-em-for-local-sizing) +1. [동영상 자동재생 감추기](#hide-autoplay-videos-that-arent-muted) +1. [Flexible Type의 `:root` 사용하기](#use-root-for-flexible-type) +1. [모바일 환경을 위한 `font-size` 요소 설정](#set-font-size-on-form-elements-for-a-better-mobile-experience) +1. [포인터 이벤트를 사용한 마우스 이벤트 제어](#use-pointer-events-to-control-mouse-events) +1. [간격으로 사용되는 줄 바꿈에서 `display: none` 을 설정하십시오.](#set-display-none-on-line-breaks-being-used-as-spacing) + + +
+ +### CSS Reset을 사용 + +CSS reset은 스타일 요소들을 통해 백지 상태에서 다른 브라우저간의 스타일의 일관성을 강화하는데 도움을 줍니다. 또한 [Normalize](http://necolas.github.io/normalize.css/), _et al._, 와 같은 CSS 리셋 라이브러리를 통해 더 쉽게 reset 형태를 취할 수 있습니다. + +```css +*, +*::before, +*::after { + box-sizing: border-box; + margin: 0; + padding: 0; +} +``` + + +이제 요소는 마진과 패딩을 배제하고, `box-sizing`은 CSS 박스 모델을 통해 관리됩니다. + +#### [데모](http://codepen.io/AllThingsSmitty/pen/kkrkLL) + +**Note:** 당신이 아래의 [`box-sizing`을 컴포넌트마다 변경](#inherit-box-sizing) 팁을 따를 경우 `box-sizing` 프로퍼티를 선택하지 않을 수 있습니다. + +[목차로 돌아가기](#table-of-contents) + + + +
+ +### `box-sizing`을 컴포넌트마다 변경 + +`html`에서 `box-sizing`을 계승하게 합니다: + +```css +html { + box-sizing: border-box; +} + +*, +*::before, +*::after { + box-sizing: inherit; +} +``` + +이것은 다른 플러그인과 컴포넌트에서 `box-sizing`을 변경하는 것을 용이하게 합니다. + +#### [데모](https://css-tricks.com/inheriting-box-sizing-probably-slightly-better-best-practice/) + +[목차로 돌아가기](#table-of-contents) + + +
+ +### 모든 프로퍼티를 리셋하는 대신에 `unset`를 쓴다 + +요소들을 리셋할 경우, 각각의 속성을 리셋할 필요가 없습니다. + +```css +button { + background: none; + border: none; + color: inherit; + font: inherit; + outline: none; + padding: 0; +} +``` + +요소의 속성 `all` 생략형을 통해 지정하고 `unset`을 통해 모든 요소를 초기값으로 설정할 수 있습니다. + +```css +button { + all: unset; +} +``` + +[목차로 돌아가기](#table-of-contents) + + +
+ +### `:not()` 를 사용하여 보더를 삭제 + +Border를 넣거나... + +```css +/* 보더 추가 */ +.nav li { + border-right: 1px solid #666; +} +``` + +...마지막 요소를 없애기 보다는... + +```css +/* 보더 삭제 */ +.nav li:last-child { + border-right: none; +} +``` + +...`:not()`을 사용하여 코드를 간단히 지정할 수 있습니다. + +```css +.nav li:not(:last-child) { + border-right: 1px solid #666; +} +``` + +CSS 선택자는 사람이 설명하는 방식 그대로 경계를 정의합니다. + +#### [데모](http://codepen.io/AllThingsSmitty/pen/LkymvO) + +[목차로 돌아가기](#table-of-contents) + + +
+ +### 글꼴이 로컬로 설치되어 있는지 확인 + +글꼴을 원격으로 가져 오기 전에 글꼴이 로컬에 설치되어 있는지 확인할 수 있으며 이는 좋은 성능 팁입니다. + +```css +@font-face { + font-family: "Dank Mono"; + src: + /* 풀네임 */ + local("Dank Mono"), + /* 포스트 스크립트명 */ + local("Dank-Mono"), + /* 아니면 다운로드도 가능! */ + url("//...a.server/fonts/DankMono.woff"); +} + +code { + font-family: "Dank Mono", system-ui-monospace; +} +``` + +이 팁과 [데모](https://codepen.io/argyleink/pen/VwYJpgR)를 공유 한 Adam Argyle의 모자 팁. + +[목차로 돌아가기](#table-of-contents) + + +
+ +### `body`에 `line-height` 넣기 + +`body`요소에서`line-height`를 지정할 때 `p`,`h*`, _et al_ 등에 그 값이 계승되기 때문에 각각`line-height`을 지정할 필요가 없습니다. + +```css +body { + line-height: 1.5; +} +``` + +이 방법으로 텍스트 요소가 `body`의 속성을 쉽게 계승할 수 있습니다. + +#### [데모](http://codepen.io/AllThingsSmitty/pen/VjbdYd) + +[목차로 돌아가기](#table-of-contents) + + +
+ +### 폼 요소에`: focus`를 설정하기 + +키보드 사용자는 포커스를 사용하여 키보드 이벤트의 위치를 결정합니다. 폼 요소에 집중할 수 있게 해주며, 브라우저의 기본 구현을 일관성있게 만듭니다. + +```css +a:focus, +button:focus, +input:focus, +select:focus, +textarea:focus { + box-shadow: none; + outline: #000 dotted 2px; + outline-offset: .05em; +} +``` + +#### [데모](https://codepen.io/AllThingsSmitty/pen/ePzoOP/) + +[목차로 돌아가기](#table-of-contents) + + +
+ +### 전부 Vertically-Center로 만들기 + +농담이 아니라, 진짜 전부 중앙으로 배치가 가능합니다. + +```css +html, +body { + height: 100%; + margin: 0; +} + +body { + -webkit-align-items: center; + -ms-flex-align: center; + align-items: center; + display: -webkit-flex; + display: flex; +} +``` + +무언가를 중앙으로 배치하고 싶으신가요? 가로로, 세로로 ...뭐든지, 어떤 때라도, 어디서든? CSS-Tricks의 [가이드](https://css-tricks.com/centering-css-complete-guide/)를 통해 그 모든 것을 해보세요! + +#### [데모](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) + +[목차로 돌아가기](#table-of-contents) + + +
+ +### 리스트를 콤마로 나누기 + +Make list items look like a real, comma-separated list: +리스트 아이템을 콤마를 통해 나눕니다. + +```css +ul > li:not(:last-child)::after { + content: ","; +} +``` + +`:not()` 을 사용할 때 리스트의 마지막 아이템에는 콤마를 사용하지 않도록 합니다. + +**Note:** 이 팁의 경우 접근성이 떨어질 수 있습니다. 특히, 스크린 사용자에게는요. 또한 브라우저에서의 복사/붙여넣기는 CSS를 통해 생성한 콘텐츠에서는 사용 불가능하므로 주의해 주세요. + +[목차로 돌아가기](#table-of-contents) + + +
+### Negative `nth-child`를 사용하여 아이템 나누기 + +Negative `nth-child`를 사용하여 n분의 1로 아이템을 나눌 수 있습니다. + +```css +li { + display: none; +} + +/* 1에서 3까지의 선택하고 보여주기 */ +li:nth-child(-n+3) { + display: block; +} +``` + +[`:not()`](#use-not-to-applyunapply-borders-on-navigation), 를 사용해 봅시다. + +```css +/* 처음 3개를 제외한 모든 아이템 보여주기 */ +li:not(:nth-child(-n+3)) { + display: none; +} +``` + +#### [데모](http://codepen.io/AllThingsSmitty/pen/WxjKZp) + +[목차로 돌아가기](#table-of-contents) + + + +
+ +### SVG를 아이콘으로 사용하기 + +SVG를 아이콘으로 사용할 이유는 없지만: + +```css +.logo { + background: url("logo.svg"); +} +``` + +SVG는 [IE9](http://caniuse.com/#search=svg) 이후부터 지원되고 있습니다. + +**Note:** 버튼이 SVG로 만들어진 경우, 접근성을 높이기 위해 이 방법을 사용해 보세요. + +```css +.no-svg .icon-only::after { + content: attr(aria-label); +} +``` + +[목차로 돌아가기](#table-of-contents) + + +### "Lobotomized Owl" Selector 사용하기 + +이상한 이름이지만 (`*`)와 (`+`)와 함께 사용하면 강력한 CSS의 가능성을 제공합니다. + +```css +* + * { + margin-top: 1.5em; +} +``` + +이 예시에서는, 모든 요소가 `margin-top: 1.5em`를 따릅니다. + +"lobotomized owl" selector에 대해 더 알고싶으시다면 *A List Apart* [Heydon Pickering's post](http://alistapart.com/article/axiomatic-css-and-lobotomized-owls)의 이 문서를 읽어보세요. + +#### [데모](http://codepen.io/AllThingsSmitty/pen/grRvWq) + +[목차로 돌아가기](#table-of-contents) + + +
+ +### CSS로 구현된 슬라이더에 `max-height` 사용하기 + +CSS에서 구현된 슬라이더는`max-height`을`overflow:hidden;`와 함께 사용하세요. + +```css +.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 +hover시 `max-height`를 요소를 확장 오버플로우의 결과로 슬라이더에 표시됩니다. + +[목차로 돌아가기](#table-of-contents) + + +
+ +### 테이블 셀의 너비 균등하게 하기 + +테이블의 각 셀의 너비를 균등하려면`table-layout:fixed;`를 사용해 간단히 할 수 있습니다. + +```css +.calendar { + table-layout: fixed; +} +``` + +고통 없는 테이블 디스플레이를 가능하게 합니다 + +#### [데모](http://codepen.io/AllThingsSmitty/pen/jALALm) + +[목차로 돌아가기](#table-of-contents) + + +
+ +### Flexbox의 Margin Hack 제거 + +column gutter을 사용할 때 flexbox의 `space-between` 요소를 사용하여 `nth-`, `first-`, `last-child`를 사용하지 않게 해줍니다. + +```css +.list { + display: flex; + justify-content: space-between; +} + +.list .person { + flex-basis: 23%; +} +``` + +column gutter는 이제 이벤트 공간에 표시됩니다. + +[목차로 돌아가기](#table-of-contents) + + + + +### 링크에 텍스트가 없을 때의 url 표시 + +링크의`href`속성에 링크의 텍스트 값이 없을 경우, 아래의 CSS를 사용하면 링크처의 URL을 표시합니다. + +```css +a[href^="http"]:empty::before { + content: attr(href); +} +``` + +상당이 편리한 기능입니다. + +#### [데모](http://codepen.io/AllThingsSmitty/pen/zBzXRx) + +[목차로 돌아가기](#table-of-contents) + + + + +### "Default" 링크 스타일 + +"default" 링크에 스타일 추가하기: + +```css +a[href]:not([class]) { + color: #008000; + text-decoration: underline; +} +``` + +이것은 보통 class속성이 없는 링크에`:not`을 사용하여 CMS로 삽입됩니다. 상속(cascade)문제 없이 차별화 할 수 있습니다. + +[목차로 돌아가기](#table-of-contents) + + +
+ +### 내재 비율의 박스 + +당신이 top, bottom 패딩을 지정하는 것 만으로 내제된 비율의 박스를 생성합니다. + +```css +.container { + height: 0; + padding-bottom: 20%; + position: relative; +} + +.container div { + border: 2px dashed #ddd; + height: 100%; + left: 0; + position: absolute; + top: 0; + width: 100%; +} +``` + +20%를 패딩으로 사용하면 높이를 너비의 20%와 동일하게 합니다.뷰 포트의 너비와 상관 없이, 자식의 div는 이 비율 (100% / 20% = 5:1)를 유지합니다. + +#### [데모](http://codepen.io/AllThingsSmitty/pen/jALZvE) + +[목차로 돌아가기](#table-of-contents) + + +
+ +### 깨진 링크의 이미지 스타일 + +CSS를 통해 링크가 깨진 이미지를 사용자 친화적으로 만듭니다. + +```css +img { + display: block; + font-family: sans-serif; + font-weight: 300; + height: auto; + line-height: 2; + position: relative; + text-align: center; + width: 100%; +} +``` + +또는 다음 방법을 통해 사용자에게 깨진 링크에 대한 메세지를 전달하는 것도 가능합니다. + +```css +img::before { + content: "죄송하지만 이 이미지에 문제가 있습니다 :("; + display: block; + margin-bottom: 10px; +} + +img::after { + content: "(url: " attr(src) ")"; + display: block; + font-size: 12px; +} +``` + +이 스탕일링 패턴을 다음 링크에서 배울 수 있습니다.[Ire Aderinokun](https://github.com/ireade/)'s [original post](http://bitsofco.de/styling-broken-images/). + +[목차로 돌아가기](#table-of-contents) + + + +
+ +### 글로벌 사이즈 지정에 `rem`; 로컬  사이즈 지정에 `em` + +베이스 폰트 크기를 (`html { font-size: 100%; }`)를 통해 지정하고, 텍스트 요소를 `em`에서 지정합니다. + +```css +h2 { + font-size: 2em; +} + +p { + font-size: 1em; +} +``` + +`rem`을 통해 모듈의 폰트 사이즈를 지정해 봅시다: + +```css +article { + font-size: 1.25rem; +} + +aside .module { + font-size: .9rem; +} +``` + +이제 각 모듈별로 관리하면 관리가 쉽고 스탕일링이 간편해 집니다. + +[목차로 돌아가기](#table-of-contents) + + +
+ +### 동영상 자동재생 감추기 + +이것은 스타일 시트의 커스텀에서 유용한 트릭입니다. 유저가 페이지가 로드될 때 소리가 자동 재생될 때 겪는 부담을 줄여줍니다. 만약 소리를 끌 수 없다면, 차라리 동영상을 보여주지 마세요. + +```css +video[autoplay]:not([muted]) { + display: none; +} +``` + +다시한 한 번[`:not()`](#use-not-to-applyunapply-borders-on-navigation)을 사용하는 것의 편리함을 보여줍니다. + +[목차로 돌아가기](#table-of-contents) + + +
+ +### Flexible Type의 `:root` 사용하기 + +`:root`를 사용하여 반응형 레이아웃의 타입 폰트 사이즈를 뷰 포트마다 적용할 수 있게 합니다. 뷰 포트의 높이와 너비를 바탕으로 폰트 크기를 정의할 수 있습니다. + +```css +:root { + font-size: calc(1vw + 1vh + .5vmin); +} +``` + +`:root`를 정의된 값을 바탕으로 `root em`을 사용할 수 있습니다. + +```css +body { + font: 1rem/1.6 sans-serif; +} +``` + +#### [데모](http://codepen.io/AllThingsSmitty/pen/XKgOkR) + +[목차로 돌아가기](#table-of-contents) + + +
+ +### 모바일 환경을 위한 `font-size` 요소 설정 + +iOS Safari, _et al_ 과 같은 모바일 브라우저에서 `` dnależy dodać `font-size` do reguły selektora: + +```css +input[type="text"], +input[type="number"], +select, +textarea { + font-size: 16px; +} +``` + +:dancer: + +[Powrót do spisu treści](#Powrót-do-spisu-treści) + + +### Użyj zdarzeń wskaźnika do sterowania zdarzeniami myszy + +[Pointer events](https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events) umożliwiają określenie sposobu interakcji myszy z elementem, na które kilka. Aby wyłączyć domyślne zdarzenie wskaźnika na przycisku, na przykład: + +```css +button:disabled { + opacity: .5; + pointer-events: none; +} +``` + +To takie proste. + +[Powrót do spisu treści](#Powrót-do-spisu-treści) + + +### Ustaw `display: none` na Podziały linii używane jako odstępy + +Jak zauważył [Harry Roberts](https://twitter.com/csswizardry/status/1170835532584235008), może to pomóc zapobiec korzystaniu przez użytkowników CMS z dodatkowych podziałów linii dla odstępów: + +```css +br + br { + display: none; +} +``` + +[Powrót do spisu treści](#Powrót-do-spisu-treści) + + +## Wsparcie + +Wersje aktualne Chrome, Firefox, Safari, e Edge. + +[Powrót do spisu treści](#Powrót-do-spisu-treści) \ No newline at end of file diff --git a/translations/pt-BR/README.md b/translations/pt-BR/README.md index 55fac553..8a1498cf 100644 --- a/translations/pt-BR/README.md +++ b/translations/pt-BR/README.md @@ -1,10 +1,10 @@ -

- light bulb icon -

+
+ light bulb icon +
# CSS Protips [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) -Uma coleção de dicas para elevar suas habilidades de CSS. +Uma coleção de dicas para aumentar suas habilidades no CSS. > Dê uma olhada em mais algumas [listas fantásticas](https://github.com/sindresorhus/awesome/) mantidas por [@sindresorhus](https://github.com/sindresorhus/). @@ -13,31 +13,110 @@ Uma coleção de dicas para elevar suas habilidades de CSS. * [Protips](#protips) * [Suporte](#suporte) -* [Contribuições](../../CONTRIBUTING.md) +* [Guia de Contribuições](../../CONTRIBUTING.md) ## Protips +1. [Use um Reset CSS](#use-um-reset-css) +1. [Herde o `box-sizing`](#herde-o-box-sizing) +1. [Use `unset` em vez de redefinir todas as propriedades](#use-unset-em-vez-de-redefinir-todas-as-propriedades) 1. [Use `:not()` para Aplicar/Remover Bordas](#use-not-para-aplicarremover-bordas) +1. [Verifique se a fonte está instalada localmente](#verifique-se-a-fonte-está-instalada-localmente) 1. [Defina o `line-height` no `body`](#defina-o-line-height-no-body) +1. [Definir `:focus` para elementos de formulário](#definir-focus-para-elementos-de-formulário) 1. [Alinhe Elementos Verticalmente](#alinhe-elementos-verticalmente) +1. [Use `aspect-ratio` ao invés de Height/Width](#use-aspect-ratio-ao-invés-de-heightwidth) 1. [Listas Separadas por Vírgula](#listas-separadas-por-vírgula) 1. [Selecione Itens Usando `nth-child` Negativo](#selecione-itens-usando-nth-child-negativo) 1. [Ícones SVG](#Ícones-svg) 1. [Use o Seletor "Lobotomized Owl"](#use-o-seletor-lobotomized-owl) 1. [Sliders em CSS com `max-height`](#sliders-em-css-com-max-height) -1. [Herde o `box-sizing`](#herde-o-box-sizing) 1. [Tabelas com Células de Tamanho Igual](#tabelas-com-células-de-tamanho-igual) 1. [Esqueça as "Margin Hacks", use Flexbox](#esqueça-as-margin-hacks-use-flexbox) 1. [Use Seletores de Atributo em Links Vazios](#use-seletores-de-atributo-em-links-vazios) +1. [Controle Melhor a Especificidade Com `:is()`](#controle-melhor-a-especificidade-com-is) 1. [Estilize Links "Default"](#estilize-links-default) -1. [Espaçamento Vertical Consistente](#espaçamento-vertical-consistente) 1. [Div com Proporção de Tela Fixa](#div-com-proporção-de-tela-fixa) 1. [Estilize Imagens Quebradas](#estilize-imagens-quebradas) 1. [Use `rem` para Definir Tamanhos Globais; Use `em` para Definir Tamanhos Locais](#use-rem-para-definir-tamanhos-globais-use-em-para-definir-tamanhos-locais) 1. [Esconda Vídeos em Autoplay Que Não Estejam no Mudo](#esconda-vídeos-em-autoplay-que-não-estejam-no-mudo) -1. [Use `:root` para uma Typografia Flexível](#use-root-para-uma-typografia-flexível) -1. [Defina `font-size` em Elementos de Formulário para uma Melhor Experiência Mobile](#set-font-size-on-form-elements-for-a-better-mobile-experience) +1. [Use `:root` para uma Tipografia Flexível](#use-root-para-uma-tipografia-flexível) +1. [Defina `font-size` em Elementos de Formulário para uma Melhor Experiência Mobile](#defina-font-size-em-elementos-de-formulário-para-uma-melhor-experiência-mobile) +1. [Use eventos de ponteiro para controlar eventos do mouse](#use-eventos-de-ponteiro-para-controlar-eventos-do-mouse) +1. [Definir `display: none` em quebras de linha usadas como espaçamento](#definir-display-none-em-quebras-de-linha-usadas-como-espaçamento) +1. [Use `:empty` para Esconder Eelementos HTML Vazios](#use-empty-para-esconder-elementos-html-vazios) + +### Use um Reset CSS + +Resetar o CSS vai te ajudar a manter a consistência de estilo em diferentes navegadores com um ponto de partida limpo para elementos de estilo. Você pode usar a biblioteca de reset CSS como [Normalize](http://necolas.github.io/normalize.css/), ou se preferir, usar uma abordagem mais simplificada.: + +```css +*, +*::before, +*::after { + box-sizing: border-box; + margin: 0; + padding: 0; +} +``` + +Agora os elementos estarão sem margens, preenchimento e `box-sizing`. Te permitindo gerenciar o layout com o seu CSS. + +#### [Exemplo](http://codepen.io/AllThingsSmitty/pen/kkrkLL) + +**Nota:** Se você seguir a dica [Herde o box-sizing](#herde-o-box-sizing) abaixo você pode optar por não incluir a propriedade `box-sizing` em sua redefinição de CSS. + +[voltar ao índice](#Índice) + + +### Herde o `box-sizing` + +Faça com que o `box-sizing` seja herdado do `html`: + +```css +html { + box-sizing: border-box; +} + +*, +*::before, +*::after { + box-sizing: inherit; +} +``` + +Assim fica fácil de alterar o `box-sizing` em plugins ou outros componentes que tenham um comportamento diferente. + +#### [Exemplo](https://css-tricks.com/inheriting-box-sizing-probably-slightly-better-best-practice/) + +[voltar ao índice](#Índice) + + +### Use `unset` em vez de redefinir todas as propriedades + +Ao redefinir as propriedades de um elemento, não é necessário redefinir cada propriedade individual: + +```css +button { + background: none; + border: none; + color: inherit; + font: inherit; + outline: none; + padding: 0; +} +``` + +Você pode especificar todas as propriedades de um elemento usando a abreviação `all`. Definir o valor como `unset` altera as propriedades de um elemento para seus valores iniciais: + +```css +button { + all: unset; +} +``` + +[voltar ao índice](#Índice) ### Use `:not()` para Aplicar/Remover Bordas @@ -60,7 +139,7 @@ Ao invés de colocar a borda… } ``` -…utilize a _pseudo-class_ `:not()` para aplicar a borda apenas nos elementos corretos: +…utilize a _pseudo-classe_ `:not()` para aplicar a borda apenas nos elementos corretos: ```css .nav li:not(:last-child) { @@ -68,9 +147,37 @@ Ao invés de colocar a borda… } ``` -Claro, você poderia usar `.nav li + li` ou ainda `.nav li:first-child ~ li`, mas usando `:not()` a intenção fica mais clara e o seletor CSS passa a definir a borda de uma maneira que nós humanos entendemos mais claramente. +O seletor CSS define a borda da maneira que um humano a descreveria. + +#### [Exemplo](http://codepen.io/AllThingsSmitty/pen/LkymvO) + +[voltar ao índice](#Índice) -[voltar ao índice](#table-of-contents) + +### Verifique se a fonte está instalada localmente + +Você pode verificar se uma fonte está instalada localmente antes de buscá-la remotamente, o que também é uma boa dica de desempenho. + +```css +@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; +} +``` + +Dica de chapéu para Adam Argyle por compartilhar este protip e [exemplo](https://codepen.io/argyleink/pen/VwYJpgR). + +[voltar ao índice](#Índice) ### Defina o `line-height` no `body` @@ -85,7 +192,30 @@ body { Dessa maneira elementos de texto vão herdar o `line-height` do `body`. -[voltar ao índice](#table-of-contents) +#### [Exemplo](http://codepen.io/AllThingsSmitty/pen/VjbdYd) + +[voltar ao índice](#Índice) + + +### Definir `:focus` para elementos de formulário + +Os usuários de teclado com visão dependem do foco para determinar onde os eventos de teclado vão na página. Faça com que os elementos do formulário se foquem e sejam consistentes com a implementação padrão do navegador: + +```css +a:focus, +button:focus, +input:focus, +select:focus, +textarea:focus { + box-shadow: none; + outline: #000 dotted 2px; + outline-offset: .05em; +} +``` + +#### [Exemplo](https://codepen.io/AllThingsSmitty/pen/ePzoOP/) + +[voltar ao índice](#Índice) ### Alinhe Elementos Verticalmente @@ -93,7 +223,8 @@ Dessa maneira elementos de texto vão herdar o `line-height` do `body`. Que bruxaria é essa? Não é bruxaria! Você realmente pode centralizar elementos verticalmente: ```css -html, body { +html, +body { height: 100%; margin: 0; } @@ -107,12 +238,42 @@ body { } ``` +...e também com CSS Grid: + +```css +body { + display: grid; + height: 100vh; + margin: 0; + place-items: center center; +} +``` + Isso não resolveu seu problema? O site CSS-Tricks tem [um guia completo](https://css-tricks.com/centering-css-complete-guide/) de como centralizar elementos com CSS. -**Aviso:** Fique atento com os [bugs](https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items) quando utilizar flexbox no IE11. +#### [Exemplo](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) + +[voltar ao índice](#Índice) -[voltar ao índice](#table-of-contents) +### Use `aspect-ratio` ao Invés de Height/Width +A propriedade `aspect-ratio` permite que você dimensione elementos facilmente e mantem a proporção largura-altura (width-to-height) consistênte. Isso é incrivelmente útil em web design responsivo para prevenir alterações no layout. Use `object-fit` com isso para prevenir quebras no layout se os valores de altura/largura das images mudar. + +```css +img { + aspect-ratio: 16 / 9; /* width / height */ + object-fit: cover; +} +``` + +Aprenda mais sobre a propriedade `aspect-ratio` neste [web.dev post](https://web.dev/articles/aspect-ratio). + +#### [Demo](https://codepen.io/AllThingsSmitty/pen/MWxwoNx/) + +> [!NOTA] +> `aspect-ratio` e `object-fit` não são suportados em IE11. + +[voltar ao índice](#Índice) ### Listas Separadas por Vírgula @@ -124,11 +285,11 @@ ul > li:not(:last-child)::after { } ``` -Utilize a _pseudo-class_ `:not()` para evitar que a vírgula seja adicionada depois do último item. +Utilize a _pseudo-classe_ `:not()` para evitar que a vírgula seja adicionada depois do último item. **Aviso:** Se considerarmos acessibilidade essa dica pode não ser ideal, especialmente para usuários de leitores de tela. Além disso, copiar e/ou colar não funcionam em conteúdo criado com CSS. Proceda com cautela. -[voltar ao índice](#table-of-contents) +[voltar ao índice](#Índice) ### Selecione Itens Usando `nth-child` Negativo @@ -146,10 +307,10 @@ li:nth-child(-n+3) { } ``` -Já que você aprendeu um pouquinho sobre como usar a _pseudo-class_ [using `:not()`](#use-not-to-applyunapply-borders-on-navigation), você pode tentar: +Já que você aprendeu um pouquinho sobre como usar a _pseudo-classe_ [using `:not()`](#use-not-to-applyunapply-borders-on-navigation), você pode tentar: ```css -/* mostrar itens de 1 a 3 */ +/* selecione todos os itens, exceto os primeiros 3 e exiba-os */ li:not(:nth-child(-n+3)) { display: none; } @@ -157,7 +318,9 @@ li:not(:nth-child(-n+3)) { Mais fácil que isso só dois disso. -[voltar ao índice](#table-of-contents) +#### [Exemplo](http://codepen.io/AllThingsSmitty/pen/WxjKZp) + +[voltar ao índice](#Índice) ### Ícones SVG @@ -175,12 +338,12 @@ A vantagem do SVG é que o ícone fica bom em qualquer resolução, além de ter **Aviso:** Se você tem botões feitos apenas com ícones SVG, a dica a seguir o ajudará a manter a acessibilidade: ```css -.no-svg .icon-only:after { +.no-svg .icon-only::after { content: attr(aria-label); } ``` -[voltar ao índice](#table-of-contents) +[voltar ao índice](#Índice) ### Use o Seletor "Lobotomized Owl" @@ -197,7 +360,9 @@ Nesse exemplo, todos os elementos acompanhados de outros elementos recebem `marg Para mais exemplos utilizando o seletor "lobotomized owl", leia [o artigo escrito por Heydon Pickering](http://alistapart.com/article/axiomatic-css-and-lobotomized-owls) no site *A List Apart*. -[voltar ao índice](#table-of-contents) +#### [Exemplo](http://codepen.io/AllThingsSmitty/pen/grRvWq) + +[voltar ao índice](#Índice) ### Sliders em CSS com `max-height` @@ -219,26 +384,7 @@ Crie _sliders_ usando apenas CSS com `max-height` e `overflow-y: hidden`: O elemento se expandirá ao valor definido no `max-height` no _hover_ e você terá um _slider_ devido ao uso do overflow. -[voltar ao índice](#table-of-contents) - - -### Herde o `box-sizing` - -Faça que o `box-sizing` seja herdado do `html`: - -```css -html { - box-sizing: border-box; -} - -*, *:before, *:after { - box-sizing: inherit; -} -``` - -Assim fica fácil de alterar o `box-sizing` em plugins ou outros componentes que tenham um comportamento diferente. - -[voltar ao índice](#table-of-contents) +[voltar ao índice](#Índice) ### Tabelas com Células de Tamanho Igual @@ -253,7 +399,9 @@ Não tem nada mais chato do que trabalhar com tabelas, mas você pode usar `tabl Tabelas sem dor de cabeça. -[voltar ao índice](#table-of-contents) +#### [Exemplo](http://codepen.io/AllThingsSmitty/pen/jALALm) + +[voltar ao índice](#Índice) ### Esqueça as "Margin Hacks", use Flexbox @@ -273,12 +421,12 @@ Quando definir o espaçamento entre as colunas, você pode deixar os seletores ` Assim as colunas ficam espaçadas uniformemente. -[voltar ao índice](#table-of-contents) +[voltar ao índice](#Índice) ### Use Seletores de Atributo em Links Vazios -Mostre links para `
` tags vazias que possuem o atributo `href`: +Mostre links para tags `` vazias que possuem o atributo `href`: ```css a[href^="http"]:empty::before { @@ -288,38 +436,52 @@ a[href^="http"]:empty::before { Mão na roda. -[voltar ao índice](#table-of-contents) +#### [Exemplo](http://codepen.io/AllThingsSmitty/pen/zBzXRx) +[voltar ao índice](#Índice) -### Estilize Links "Default" +### Controle Melhor a Especificidade Com `:is()` -Defina estilos para links "default": +A pseudoclasse `:is()` é usada para marca vários seletores de uma só vez, reduzindo a redundância e melhorando a legibilidade do código. Isso é extremamente útil para escrever seletores grandes de uma forma mais compacta. ```css -a[href]:not([class]) { - color: #008000; - text-decoration: underline; +:is(section, article, aside, nav) :is(h1, h2, h3, h4, h5, h6) { + color: green; } ``` -Dessa forma, links que são inseridos por CMS – que normalmente não possuem o atributo `class` – vão ser estilizados sem comprometer outros links. +O conjunto de regras acima é equivalente às seguintes regras do seletor de números... + +```css +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; +} +``` -[voltar ao índice](#table-of-contents) +#### [Demo](https://codepen.io/AllThingsSmitty/pen/rNRVxdx) +> [!NOTA] +> A pseudoclasse `:is()` não é suportada em IE11. -### Espaçamento Vertical Consistente +[voltar ao índice](#Índice) -Use o seletor universal dentro de um elemento para criar um espaçamento vertical consistente: +### Estilize Links "Default" + +Defina estilos para links "default": ```css -.intro > * { - margin-bottom: 1.25rem; +a[href]:not([class]) { + color: #008000; + text-decoration: underline; } ``` -Com um espaçamento vertical consistente o seu conteúdo fica visualmente mais agradável de ler. +Dessa forma, links que são inseridos por CMS – que normalmente não possuem o atributo `class` – vão ser estilizados sem comprometer outros links. -[voltar ao índice](#table-of-contents) +[voltar ao índice](#Índice) ### Div com Proporção de Tela Fixa @@ -345,7 +507,9 @@ Para criar uma div com proporção de tela fixa, tudo que você precisa fazer é Se você usar 20% no `padding` a altura da div vai ser igual a 20% de sua largura. Independente da largura do _viewport_, a div filho vai sempre manter a proporção de tela (100% / 20% = 5:1). -[voltar ao índice](#table-of-contents) +#### [Exemplo](http://codepen.io/AllThingsSmitty/pen/jALZvE) + +[voltar ao índice](#Índice) ### Estilize Imagens Quebradas @@ -355,7 +519,7 @@ Faça com que imagens quebradas fiquem esteticamente mais agradáveis com um pou ```css img { display: block; - font-family: Helvetica, Arial, sans-serif; + font-family: sans-serif; font-weight: 300; height: auto; line-height: 2; @@ -365,16 +529,16 @@ img { } ``` -Agora adicione regras com _pseudo-elements_ para mostrar uma mensagem e a URL da imagem quebrada: +Agora adicione regras com _pseudo-elementos_ para mostrar uma mensagem e a URL da imagem quebrada: ```css -img:before { +img::before { content: "Desculpe, a imagem abaixo não pode ser carregada :("; display: block; margin-bottom: 10px; } -img:after { +img::after { content: "(url: " attr(src) ")"; display: block; font-size: 12px; @@ -383,12 +547,12 @@ img:after { Leia mais sobre como estilizar imagens quebradas no [artigo original](http://bitsofco.de/styling-broken-images/) por [Ire Aderinokun](https://github.com/ireade/). -[voltar ao índice](#table-of-contents) +[voltar ao índice](#Índice) ### Use `rem` para Definir Tamanhos Globais; Use `em` para Definir Tamanhos Locais -Depois de definir o tamanho de fonte base na raíz (`html { font-size: 16px; }`), defina o tamanho de fonte para elementos de texto utilizando `em`: +Depois de definir o tamanho de fonte base na raíz (`html { font-size: 100%; }`), defina o tamanho de fonte para elementos de texto utilizando `em`: ```css h2 { @@ -414,7 +578,7 @@ aside .module { Assim fica mais fácil de estilizar e manter cada módulo, além de ser flexível. -[voltar ao índice](#table-of-contents) +[voltar ao índice](#Índice) ### Esconda Vídeos em Autoplay Que Não Estejam no Mudo @@ -427,14 +591,14 @@ video[autoplay]:not([muted]) { } ``` -E aqui mais uma entre as muitas vantagens de usar a _pseudo-class_ [`:not()`](#use-not-to-applyunapply-borders-on-navigation). +E aqui mais uma entre as muitas vantagens de usar a _pseudo-classe_ [`:not()`](#use-not-to-applyunapply-borders-on-navigation). -[voltar ao índice](#table-of-contents) +[voltar ao índice](#Índice) -### Use `:root` para uma Typografia Flexível +### Use `:root` para uma Tipografia Flexível -O tamanho de fonte de um site _responsive_ deveria ser ajustável de acordo com cada _viewport_. Você pode calcular o tamanho da fonte baseado na largura e na altura do _viewport_ usando `:root`: +O tamanho de fonte de um site _responsivo_ deveria ser ajustável de acordo com cada _viewport_. Você pode calcular o tamanho da fonte baseado na largura e na altura do _viewport_ usando `:root`: ```css :root { @@ -446,14 +610,15 @@ Assim você pode utilizar a unidade de medida `root em` baseada no valor calcula ```css body { - font: 1em/1.6 sans-serif; + font: 1rem/1.6 sans-serif; } ``` -[voltar ao índice](#table-of-contents) +#### [Exemplo](http://codepen.io/AllThingsSmitty/pen/XKgOkR) + +[voltar ao índice](#Índice) -
### Defina `font-size` em Elementos de Formulário para uma Melhor Experiência Mobile Para evitar zoom indesejado em elementos de formulários de navegadores mobile (iOS Safari, _et al_) quando um `` é selecionado, adicione `font-size` no seletor: + +```css +input[type="text"], +input[type="number"], +select, +textarea { + font-size: 16px; +} +``` + +:dancer: + +[Regressar ao índice](#Índice) + + +### Usa eventos de ponteiro para controlar eventos do mouse + +[Eventos de ponteiro](https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events) permitem que você especifique como o mouse interage com o elemento que está tocando. Para desativar o evento de ponteiro padrão em um botão, por exemplo: + +```css +button:disabled { + opacity: .5; + pointer-events: none; +} +``` + +É simples assim. + +[Regressar ao índice](#Índice) + + +### Definir `display: none` em quebras de linha usadas como espaçamento + +Como [Harry Roberts apontou](https://twitter.com/csswizardry/status/1170835532584235008), isso pode ajudar a impedir que os usuários do CMS usem quebras de linha extras para espaçamento: + +```css +br + br { + display: none; +} +``` + +[Regressar ao índice](#Índice) + + +## Suporte + +Versões atuais do Chrome, Firefox, Safari, e Edge. diff --git a/translations/ru-RU/README.md b/translations/ru-RU/README.md index 5fd60ebf..db8c5338 100644 --- a/translations/ru-RU/README.md +++ b/translations/ru-RU/README.md @@ -1,5 +1,5 @@

- light bulb icon + light bulb icon

# Советы профессионалов CSS [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) @@ -10,38 +10,118 @@
+ ## Содержание -* [Профессиональные советы](#protips) +* [Профессиональные советы](#Профессиональные-советы) * [Поддержка](#Поддержка) * [Помощь проекту](../../CONTRIBUTING.md) -
## Профессиональные советы -1. [Используйте `:not()` для добавления / удаления границ в меню навигации](#use-not-to-applyunapply-borders-on-navigation) -1. [Добавьте `line-height` в `body`](#add-line-height-to-body) -1. [Выровнять все по вертикали](#vertically-center-anything) -1. [Списки, разделенные запятыми](#comma-separated-lists) -1. [Выбирайте элементы с использованием отрицательных значений в `пth-child`](#select-items-using-negative-nth-child) -1. [Используйте SVG для значков](#use-svg-for-icons) -1. [Используйте селектор "Лоботомированная сова"](#use-the-lobotomized-owl-selector) -1. [Используйте `max-height` для ползунков на чистом CSS](#use-max-height-for-pure-css-sliders) -1. [Наследуйте `box-sizing`](#inherit-box-sizing) -1. [Ячейки таблицы равной ширины](#equal-width-table-cells) -1. [Используйте Flexbox вместо margin](#get-rid-of-margin-hacks-with-flexbox) -1. [Используйте селектор атрибутов для пустых ссылок](#use-attribute-selectors-with-empty-links) -1. [Стиль "по умолчанию" для ссылок](#style-default-links) -1. [Постоянный вертикальный ритм](#consistent-vertical-rhythm) -1. [Блок с собственным отношением сторон](#intrinsic-ratio-boxes) -1. [Задайте стили для поломанныx изображений](#style-broken-images) -1. [Используйте `rem` для глобальных размеров; Используйте `em` для локальных размеров](#use-rem-for-global-sizing-use-em-for-local-sizing) -1. [Отключите автовоспроизведение видео с включенным звуком](#hide-autoplay-videos-that-arent-muted) -1. [Используйте `:root` для шрифтов](#use-root-for-flexible-type) -1. [Установите `font-size` для элементов формы, чтобы оптимизировать просмотр на мобильных устройствах](#set-font-size-on-form-elements-for-a-better-mobile-experience) - -
+1. [Используйте CSS Reset](#Используйте-css-reset) +1. [Наследуйте `box-sizing`](#Наследуйте-box-sizing) +1. [Используйте `unset` вместо сброса всех свойств](#Используйте-unset-вместо-сброса-всех-свойств) +1. [Используйте `:not()` для добавления / удаления границ в меню навигации](#Используйте-not-для-добавления--удаления-границ-в-меню-навигации) +1. [Проверьте, установлен ли шрифт локально](#проверьте,-установлен-ли-шрифт-локально) +1. [Добавьте `line-height` в `body`](#Добавьте-line-height-в-body) +1. [Установите `:focus` для элементов формы](#Установите-focus-для-элементов-формы) +1. [Выровнять всё по вертикали](#Выровнять-всё-по-вертикали) +1. [Используйте `aspect-ratio` вместо задания ширины, высоты](#Используйте-aspect-ratio-вместо-задания-ширины-высоты) +1. [Списки, разделенные запятыми](#Списки-разделенные-запятыми) +1. [Выбирайте элементы с использованием отрицательных значений в `nth-child`](#Выбирайте-элементы-с-использованием-отрицательных-значений-в-nth-child) +1. [Используйте SVG для значков](#Используйте-svg-для-значков) +1. [Используйте селектор "Лоботомированная сова"](#Используйте-селектор-Лоботомированная-сова) +1. [Используйте `max-height` для ползунков на чистом CSS](#Используйте-max-height-для-ползунков-на-чистом-css) +1. [Ячейки таблицы равной ширины](#Ячейки-таблицы-равной-ширины) +1. [Используйте Flexbox вместо margin](#Используйте-flexbox-вместо-margin) +1. [Используйте селектор атрибутов для пустых ссылок](#Используйте-селектор-атрибутов-для-пустых-ссылок) +1. [Управляйте специфичностью лучше, с помощью `:is()`](#Управляйте-специфичностью-лучше-с-помощью-is) +1. [Стиль "по умолчанию" для ссылок](#тиль-по-умолчанию-для-ссылокs) +1. [Блок с собственным отношением сторон](#Блок-с-собственным-отношением-сторон) +1. [Задайте стили для поломанныx изображений](#Задайте-стили-для-поломанныx-изображений) +1. [Используйте `rem` для глобальных размеров; Используйте `em` для локальных размеров](#Используйте-rem-для-глобальных-размеров-Используйте-em-для-локальных-размеров) +1. [Отключите автовоспроизведение видео с включенным звуком](#Отключите-автовоспроизведение-видео-с-включенным-звуком) +1. [Используйте `:root` для шрифтов](#Используйте-root-для-шрифтов) +1. [Установите `font-size` для элементов формы, чтобы оптимизировать просмотр на мобильных устройствах](#Установите-font-size-для-элементов-формы-чтобы-оптимизировать-просмотр-на-мобильных-устройствах) +1. [Использовать события указателя для управления событиями мыши](#Использовать-события-указателя-для-управления-событиями-мыши) +1. [Установите `display: none` на разрывы строк, используемые как интервалы](#Установите-display-none-на-разрывы-строк-используемые-как-интервалы) +1. [Используйте `:empty`, чтобы скрыть пустые HTML элементы](#Используйте-empty-чтобы-скрыть-пустые-HTML-элементы) + + +### Используйте CSS Reset + +Сброс CSS помогает обеспечить согласованность стилей между различными браузерами и с чистого листа начать оформление элементов. Вы можете использовать CSS библиотеки сброса такие как [Normalize](http://necolas.github.io/normalize.css/) и др., или вы можете использовать более простой способ сброса: + +```css +*, +*::before, +*::after { + box-sizing: border-box; + margin: 0; + padding: 0; +} +``` + +Теперь для всех элементов свойства margin и padding будут равны нулю, а `box-sizing: border-box` позволяет указывать размеры всему блоку, а не его содержимому. + +#### [Демо](http://codepen.io/AllThingsSmitty/pen/kkrkLL) + +**Примечание:** Если вы будете следовать совету [Наследуйте `box-sizing`](#inherit-box-sizing), то вы можете не включать свойство `box-sizing` в ваш CSS Reset. + +[вернуться к оглавлению](#table-of-contents) + + +### Наследуйте `box-sizing` + +Пусть `box-sizing` будет унаследован от `html`: + +```css +html { + box-sizing: border-box; +} + +*, +*::before, +*::after { + box-sizing: inherit; +} +``` + +Так значительно проще изменять `box-sizing` в плагинах или других компонентах, которые задают иное поведение. + +#### [Демо](https://css-tricks.com/inheriting-box-sizing-probably-slightly-better-best-practice/) + +[вернуться к оглавлению](#table-of-contents) + + +### Используйте `unset` вместо сброса всех свойств + +При сбросе свойств элемента нет необходимости сбросить каждое отдельное свойство: + +```css +button { + background: none; + border: none; + color: inherit; + font: inherit; + outline: none; + padding: 0; +} +``` + +Вы можете указать все свойства элемента, используя сокращенное выражение `all`. Установка значения `unset` изменяет свойства элемента на их начальные значения: + +```css +button { + all: unset; +} +``` + +[вернуться к оглавлению](#table-of-contents) + + ### Используйте `:not()` для добавления / удаления границ в меню навигации Вместо того, чтобы добавлять границу... @@ -70,12 +150,39 @@ } ``` -Конечно, вы можете использовать `.nav li + li` или даже `.nav li:first-child ~ li`, но с `:not()` намерение понятнее, а селектор CSS определяет границу на человеческом языке. +Селектор CSS определяет границу так, как ее описывает человек. + +#### [Демо](http://codepen.io/AllThingsSmitty/pen/LkymvO) + +[вернуться к оглавлению](#table-of-contents) + + +### Проверьте, установлен ли шрифт локально + +Вы можете проверить, установлен ли шрифт локально, прежде чем извлекать его удаленно, что также является хорошим показателем производительности. + +```css +@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; +} +``` + +Шляпный совет Адаму Аргайлу за то, что он поделился этим опытом и [примером](https://codepen.io/argyleink/pen/VwYJpgR). [вернуться к оглавлению](#table-of-contents) -
### Добавьте `line-height` в `body` Вам вовсе не требуется добавлять свойство `line-height` к каждому `<р>`, ``, _и т.д._. по отдельности. Вместо этого добавьте его в `body`: @@ -88,16 +195,37 @@ body { Таким образом текстовые элементы легко могут наследовать свойство от `body`. +#### [Демо](http://codepen.io/AllThingsSmitty/pen/VjbdYd) + [вернуться к оглавлению](#table-of-contents) -
-### Выровнять все по вертикали +### Установите `:focus` для элементов формы -Нет, это не черная магия, вы действительно можете расположить элементы по центру по вертикали: +Приоритетные пользователи клавиатуры полагаются на фокус, чтобы определить, где события клавиатуры идут на странице. Сделайте фокус для элементов формы выделяющимися и последовательными, а затем реализацией браузера по умолчанию: ```css -html, body { +a:focus, +button:focus, +input:focus, +select:focus, +textarea:focus { + box-shadow: none; + outline: #000 dotted 2px; + outline-offset: .05em; +} +``` + +[вернуться к оглавлению](#table-of-contents) + + +### Выровнять всё по вертикали + +Нет, это не чёрная магия, вы действительно можете расположить элементы по центру по вертикали: + +```css +html, +body { height: 100%; margin: 0; } @@ -111,14 +239,42 @@ body { } ``` +...а также с помощью CSS Grid: + +```css +body { + display: grid; + height: 100vh; + margin: 0; + place-items: center center; +} +``` + Хотите разместить по центру что-то еще? Вертикально, горизонтально...что угодно, в любое время и в любом месте? У нас есть [хорошая статья](https://css-tricks.com/centering-css-complete-guide/) которая научит всему этому. -**Примечание:** Будьте осторожны с некоторыми [багами](https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items) flexbox в IE11. +#### [Демо](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) + +[вернуться к оглавлению](#table-of-contents) + + +### Используйте `aspect-ratio` вместо задания ширины, высотыhttps://onelove-agency.ru/web/october2024 + +Свойство `aspect-ratio` позволяет легко изменять размеры элементов и поддерживать постоянное соотношение ширины и высоты. Это невероятно полезно в отзывчивом веб-дизайне для предотвращения смещения макета. Используйте `object-fit` вместе с ним, чтобы не нарушить верстку при изменении значений высоты/ширины изображений. + +```css +img { + aspect-ratio: 16 / 9; /* ширина / высота */ + object-fit: cover; +} +``` + +Подробнее о свойстве ` aspect-ratio` читайте в этой статье [web.dev post](https://web.dev/articles/aspect-ratio). + +#### [Демо](https://codepen.io/AllThingsSmitty/pen/MWxwoNx/) [вернуться к оглавлению](#table-of-contents) -
### Списки, разделенные запятыми Сделайте список похожим на настоящий, разделенный запятыми список: @@ -136,8 +292,7 @@ ul > li:not(:last-child)::after { [вернуться к оглавлению](#table-of-contents) -
-### Выбирайте элементы с использованием отрицательных значений в `пth-child` +### Выбирайте элементы с использованием отрицательных значений в `nth-child` Используйте отрицательные значения в `nth-child` в CSS для выбора элементов с 1 по n. @@ -155,7 +310,7 @@ li:nth-child(-n+3) { Или, так как вы уже немного познакомились [с `:not()`](#use-not-to-applyunapply-borders-on-navigation), попробуйте: ```css -/* выбирает и отображает элементы с 1 по 3 */ +/* выберите все элементы, кроме первых 3, и покажите их */ li:not(:nth-child(-n+3)) { display: none; } @@ -163,10 +318,11 @@ li:not(:nth-child(-n+3)) { Что же, это было довольно легко. +#### [Демо](http://codepen.io/AllThingsSmitty/pen/WxjKZp) + [вернуться к оглавлению](#table-of-contents) -
### Используйте SVG для значков Нет ни одной причины, чтобы не использовать SVG для значков: @@ -182,7 +338,7 @@ SVG хорошо масштабируется для всех разрешени **Примечание:** Если у вас есть кнопки, содержащие только SVG пиктограммы, и SVG не удается загрузить, то это поможет сохранить доступность кнопки: ```css -.no-svg .icon-only:after { +.no-svg .icon-only::after { content: attr(aria-label); } ``` @@ -190,7 +346,6 @@ SVG хорошо масштабируется для всех разрешени [вернуться к оглавлению](#table-of-contents) -
### Используйте селектор "Лоботомированная сова" Название, безусловно, странное, но используя универсальный селектор (`*`) с соседним селектором (`+`), мы получаем мощное правило CSS: @@ -205,10 +360,11 @@ SVG хорошо масштабируется для всех разрешени Более подробную информацию о селекторе "Лоботомированная сова", можно найти в [статье Heydon Pickering](http://alistapart.com/article/axiomatic-css-and-lobotomized-owls) на *A List Apart*. +#### [Демо](http://codepen.io/AllThingsSmitty/pen/grRvWq) + [вернуться к оглавлению](#table-of-contents) -
### Используйте `max-height` для ползунков на чистом CSS Реализация ползунков на чистом CSS с помощью `max-height` и `overflow hidden`: @@ -231,27 +387,6 @@ SVG хорошо масштабируется для всех разрешени [вернуться к оглавлению](#table-of-contents) -
-### Наследуйте `box-sizing` - -Пусть `box-sizing` будет унаследован от `html`: - -```css -html { - box-sizing: border-box; -} - -*, *:before, *:after { - box-sizing: inherit; -} -``` - -Так значительно проще изменять `box-sizing` в плагинах или других компонентах, которые задают иное поведение. - -[вернуться к оглавлению](#table-of-contents) - - -
### Ячейки таблицы равной ширины Иногда работа с таблицами приносит боль, в таких случаях попробуйте задать `table-layout: fixed` чтобы ячейки были одинаковой ширины: @@ -264,13 +399,14 @@ html { Даешь макеты таблиц без боли! +#### [Демо](http://codepen.io/AllThingsSmitty/pen/jALALm) + [вернуться к оглавлению](#table-of-contents) -
### Используйте Flexbox вместо margin -При работе с пробелами между колонок вы можете избавиться от псевдоклассов `пth,` `first-` и `last-child` воспользовавшись свойством flexbox `space-between`: +При работе с пробелами между колонок вы можете избавиться от псевдоклассов `nth,` `first-` и `last-child` воспользовавшись свойством flexbox `space-between`: ```css .list { @@ -288,7 +424,6 @@ html { [вернуться к оглавлению](#table-of-contents) - ### Используйте селектор атрибутов для пустых ссылок Отображайте ссылки, когда элемент `
` пустой, но есть ссылка в атрибуте `href`: @@ -301,43 +436,53 @@ a[href^="http"]:empty::before { Это очень удобно. +#### [Демо](http://codepen.io/AllThingsSmitty/pen/zBzXRx) + [вернуться к оглавлению](#table-of-contents) - -### Стиль "по умолчанию" для ссылок +### Управляйте специфичностью лучше, с помощью `:is() -Добавьте для ссылок стиль "по умолчанию": +Псевдокласс `:is()` используется для одновременного обращения к нескольким селекторам, что уменьшает избыточность и улучшает читаемость кода. Это невероятно полезно для написания больших селекторов в более компактной форме. ```css -a[href]:not([class]) { - color: #008000; - text-decoration: underline; +:is(section, article, aside, nav) :is(h1, h2, h3, h4, h5, h6) { + color: green; } ``` -Теперь ссылки, вставленные через CMS, которые, как правило, не имеют атрибута `class`, будут иметь отличительный признак без влияния на каскад. +Приведённый выше набор правил эквивалентен следующим правилам селектора чисел... + +```css +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; +} +``` + +#### [Демо](https://codepen.io/AllThingsSmitty/pen/rNRVxdx) [вернуться к оглавлению](#table-of-contents) -
-### Постоянный вертикальный ритм +### Стиль "по умолчанию" для ссылок -Используйте универсальный селектор (`*`) внутри элемента, чтобы создать постоянный вертикальный ритм: +Добавьте для ссылок стиль "по умолчанию": ```css -.intro > * { - margin-bottom: 1.25rem; +a[href]:not([class]) { + color: #008000; + text-decoration: underline; } ``` -Постоянный вертикальный ритм добавляет визуальную эстетику, благодаря которой читать текст гораздо проще. +Теперь ссылки, вставленные через CMS, которые, как правило, не имеют атрибута `class`, будут иметь отличительный признак без влияния на каскад. [вернуться к оглавлению](#table-of-contents) -
### Блок с собственным отношением сторон Чтобы создать блок с собственным отношением сторон, все, что вам нужно сделать, это добавить верхний или нижний padding к DIV: @@ -361,10 +506,11 @@ a[href]:not([class]) { Использование padding 20% делает высоту параллелепипеда равной 20% от его ширины. Независимо от ширины окна, дочерний DIV будет сохранять соотношение сторон (100% / 20% = 5:1). +#### [Демо](http://codepen.io/AllThingsSmitty/pen/jALZvE) + [вернуться к оглавлению](#table-of-contents) -
### Задайте стили для поломанныx изображений Сделайте поломанные изображения эстетически приятнее с CSS: @@ -372,7 +518,7 @@ a[href]:not([class]) { ```css img { display: block; - font-family: Helvetica, Arial, sans-serif; + font-family: sans-serif; font-weight: 300; height: auto; line-height: 2; @@ -391,7 +537,7 @@ img:before { margin-bottom: 10px; } -img:after { +img::after { content: "(url: " attr(src) ")"; display: block; font-size: 12px; @@ -403,10 +549,9 @@ img:after { [вернуться к оглавлению](#table-of-contents) -
### Используйте `rem` для глобальных размеров; Используйте `em` для локальных размеров -После установки базового размера шрифта всего проекта (`html { font-size: 16px; }`), установите размер шрифта для текстовых элементов через `em`: +После установки базового размера шрифта всего проекта (`html { font-size: 100%; }`), установите размер шрифта для текстовых элементов через `em`: ```css h2 { @@ -435,7 +580,6 @@ aside .module { [вернуться к оглавлению](#table-of-contents) -
### Отключите автовоспроизведение видео с включенным звуком Это отличный трюк для пользовательских стилей. Избегайте раздражения пользователя звуком из видео, которое воспроизводится автоматически при загрузке страницы. Если звук не приглушен, то не показывайте видео: @@ -451,7 +595,6 @@ video[autoplay]:not([muted]) { [вернуться к оглавлению](#table-of-contents) -
### Используйте `:root` для шрифтов Размер шрифта должен подстраиваться под каждый возможный размер экрана. Вы можете рассчитывать размер шрифта, основываясь на высоте и ширине экрана с помощью `:root`: @@ -466,17 +609,18 @@ video[autoplay]:not([muted]) { ```css body { - font: 1em/1.6 sans-serif; + font: 1rem/1.6 sans-serif; } ``` +#### [Демо](http://codepen.io/AllThingsSmitty/pen/XKgOkR) + [вернуться к оглавлению](#table-of-contents) -
### Установите `font-size` для элементов формы, чтобы оптимизировать просмотр на мобильных устройствах -Чтобы избежать масштабирования мобильными браузерами (IOS Safari, _и др_.) элементов HTML формы, когда раскрывающийся список `` нажат, добавьте `font-size` правило селектору: ```css input[type="text"], @@ -492,6 +636,52 @@ textarea { [вернуться к оглавлению](#table-of-contents) +### Использовать события указателя для управления событиями мыши + +[События указателя](https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events) позволяют указать, как мышь взаимодействует с элементом, который он трогает. Чтобы отключить событие указателя по умолчанию на кнопке, например: + +```css +button:disabled { + opacity: .5; + pointer-events: none; +} +``` + +Это так просто. + +[вернуться к оглавлению](#table-of-contents) + + +### Установите `display: none` на разрывы строк, используемые как интервалы + +Как отметил [Гарри Робертс](https://twitter.com/csswizardry/status/1170835532584235008), это может помочь пользователям CMS использовать дополнительные разрывы строк для пробелов: + +```css +br + br { + display: none; +} +``` + +[вернуться к оглавлению](#table-of-contents) + + +### Используйте `:empty`, чтобы скрыть пустые HTML элементы + +Если у вас есть HTML элементы, которые пусты, то есть их контент ещё не установлен ни CMS, ни динамической вставкой (например, `

`) и вам не нравится, что они занимают пространство вашего макета, используйте псевдо-класс `:empty`, чтобы скрыть их. + +```css +:empty { + display: none; +} +``` + +**Примечание**: Имейте в виду, что элементы с пробельными символами не считаются пустыми, например `

`. + +[вернуться к оглавлению](#table-of-contents) + + ## Поддержка -Текущие версии Chrome, Firefox, Safari, Opera, Edge, и IE11. +Текущие версии Chrome, Firefox, Safari, и Edge. + +[вернуться к оглавлению](#table-of-contents) diff --git a/translations/vn-VN/README.md b/translations/vn-VN/README.md new file mode 100644 index 00000000..04271192 --- /dev/null +++ b/translations/vn-VN/README.md @@ -0,0 +1,623 @@ +

+ light bulb icon +

+ +# CSS Protips [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) + +Một bộ gồm những tips để giúp kỹ năng CSS trở nên pro + +> For other great lists check out [@sindresorhus](https://github.com/sindresorhus/)'s curated list of [awesome lists](https://github.com/sindresorhus/awesome/). + + +## Table of Contents + +* [Protips](#protips) +* [Support](#support) +* [Translations](#translations) +* [Contribution Guidelines](CONTRIBUTING.md) + + +## Protips + +1. [Dùng CSS Reset](#dùng-css-reset) +1. [Thừa kế `box-sizing`](#thừa-kế-box-sizing) +1. [Dùng `unset` thay vì đặt lại tất cả thuộc tính](#dùng-unset-thay-vì-đặt-lại-tất-cả-thuộc-tính) +1. [Dùng `:not()` để Áp dụng/Không áp dụng các đường viền trên Điều hướng](#dùng-not-để-áp-dụngkhông-áp-dụng-các-đường-viền-trên-điều-hướng) +1. [Kiểm tra xem Phông chữ có được cài đặt cục bộ không](#kiểm-tra-xem-phông-chữ-có-được-cài-đặt-cục-bộ-không) +1. [Thêm `line-height`cho `body`](#thêm-line-height-cho-body) +1. [Đặt `:focus` cho Form Elements](#đặt-focus-cho-form-elements) +1. [Mọi thứ ở giữa theo chiều dọc](#mọi-thứ-ở-giữa-theo-chiều-dọc) +1. [Danh sách được phân tách bằng dấu phẩy](#danh-sách-được-phân-tách-bằng-dấu-phẩy) +1. [Chọn items sử dụng Negative `nth-child`](#chọn-items-sử-dụng-negative-nth-child) +1. [Dùng SVG cho Icons](#dùng-svg-cho-icons) +1. [Sử dụng "Lobotomized Owl" Selector](#sử-dụng-lobotomized-owl-selector) +1. [Dùng `max-height` cho thanh trượt CSS Sliders](#dùng-max-height-cho-thanh-trượt-css-sliders) +1. [Các ô trong bảng có chiều rộng bằng nhau](#các-ô-trong-bảng-có-chiều-rộng-bằng-nhau) +1. [Get Rid of Margin Hacks With Flexbox](#get-rid-of-margin-hacks-with-flexbox) +1. [Sử dụng thuộc tính Selectors với các liên kết trống](#sử-dụng-thuộc-tính-selectors-với-liên-kết-trống) +1. [Style "Default" Links](#style-default-links) +1. [Intrinsic Ratio Boxes](#intrinsic-ratio-boxes) +1. [Hình ảnh bị vỡ](#hình-ảnh-bị-vỡ) +1. [Dùng `rem` cho toàn cục; dùng `em` cho cục bộ](#dùng-rem-cho-toàn-cục-dùng-em-cho-cục-bộ) +1. [Ẩn các video tự động phát không bị tắt tiếng](#ẩn-các-video-tự-động-phát-không-bị-tắt-tiếng) +1. [Dùng `:root` cho Flexible Type](#dùng-root-cho-flexible-type) +1. [Đặt `font-size` trong Form Elements để có một trải nghiệm mobile tốt hơn](#đặt-font-size-trong-form-elements-để-có-một-trải-nghiệm-mobile-tốt-hơn) +1. [Dùng Pointer Events để kiểm soát mouse events](#dùng-pointer-events-để-kiểm-soát-mouse-events) +1. [Đặt `display: none` trên ngắt dòng được sử dụng làm khoảng cách](#đặt-display-none-trên-ngắt-dòng-được-sử-dụng-làm-khoảng-cách) + + +### Dùng CSS Reset + +Css resets giúp thực thi tính nhất quán về kiểu dáng trên các trình duyệt khác nhau với một phương tiện chặn rõ ràng cho các yếu tố tạo kiểu.Bạn có thể sử dụng thư viện CSS Reset như [Normalize](http://necolas.github.io/normalize.css/),hoặc bạn có thể sử dụng phương pháp đặt lại đơn giản hơn: + +```css +*, +*::before, +*::after { + box-sizing: border-box; + margin: 0; + padding: 0; +} +``` + +Bây giờ các phần tử sẽ bị loại bỏ magins và padding, và `box-sizing` cho phép bạn quản lý bố cục bằng CSS box model. + +#### [Demo](http://codepen.io/AllThingsSmitty/pen/kkrkLL) + +**Note:** Nếu bạn làm theo [Inherit `box-sizing`](#inherit-box-sizing) mẹo dưới đây, bạn có thể chọn không bao gồm `box-sizing` thuộc tính trong CSS reset của bạn. + +[back to table of contents](#table-of-contents) + + +### Thừa kế `box-sizing` + +`box-sizing` được thừa kế từ `html`: + +```css +html { + box-sizing: border-box; +} + +*, +*::before, +*::after { + box-sizing: inherit; +} +``` + +Điều này giúp bạn dễ dàng thay đổi `box-sizing` hơn trong các plugin hoặc các thành phần khác thúc đẩy hành vi khác. + +#### [Demo](https://css-tricks.com/inheriting-box-sizing-probably-slightly-better-best-practice/) + +[back to table of contents](#table-of-contents) + + +### Dùng `unset` thay vì đặt lại tất cả thuộc tính + +Khi đặt lại thuộc tính của một phần tử, không cần thiết phải đặt lại từng thuộc tính riêng lẻ: + +```css +button { + background: none; + border: none; + color: inherit; + font: inherit; + outline: none; + padding: 0; +} +``` + +Bạn có thể chỉ định tất cả các thuộc tính của một phần tử bằng cách sử dụng tất cả các viết tắt. Đặt giá trị thành không đặt sẽ thay đổi thuộc tính của phần tử thành giá trị ban đầu của chúng: + +```css +button { + all: unset; +} +``` + +[back to table of contents](#table-of-contents) + + +### Dùng `:not()` để Áp dụng / Không áp dụng các đường viền trên Điều hướng + +Thay vì đặt trên border... + +```css +/* add border */ +.nav li { + border-right: 1px solid #666; +} +``` + +...và sau đó lấy nó ra khỏi phần tử cuối cùng... + +```css +/* remove border */ +.nav li:last-child { + border-right: none; +} +``` + +...dùng `:not()` pseudo-class để chỉ áp dụng cho các phần tử bạn muốn: + +```css +.nav li:not(:last-child) { + border-right: 1px solid #666; +} +``` + +Ở đây, CSS selector được đọc như một con người sẽ mô tả nó. + +#### [Demo](http://codepen.io/AllThingsSmitty/pen/LkymvO) + +[back to table of contents](#table-of-contents) + + +### Kiểm tra xem Phông chữ có được cài đặt cục bộ không + +Bạn có thể kiểm tra xem phông chữ có được cài đặt cục bộ hay không trước khi tìm nạp từ xa, đây cũng là một mẹo hiệu suất tốt. + +```css +@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 tới Adam Argyle vì đã chia sẻ chú giải này và [demo](https://codepen.io/argyleink/pen/VwYJpgR). + +[back to table of contents](#table-of-contents) + + +### Thêm `line-height` cho `body` + +Bạn không cần thêm `line-height` cho mỗi `

`, ``... riêng biệt. Thay vào đó, hãy thêm nó vào `body`: + +```css +body { + line-height: 1.5; +} +``` + +Bằng cách này, các yếu tố văn bản có thể kế thừa từ `body` dễ dàng. + +#### [Demo](http://codepen.io/AllThingsSmitty/pen/VjbdYd) + +[back to table of contents](#table-of-contents) + + +### Đặt `:focus` cho Form Elements + +Người dùng bàn phím bị cận dựa vào tiêu điểm để xác định vị trí của các sự kiện bàn phím trong trang. Làm cho tiêu điểm cho các phần tử biểu mẫu nổi bật và nhất quán sau đó triển khai mặc định của trình duyệt: + +```css +a:focus, +button:focus, +input:focus, +select:focus, +textarea:focus { + box-shadow: none; + outline: #000 dotted 2px; + outline-offset: .05em; +} +``` + +#### [Demo](https://codepen.io/AllThingsSmitty/pen/ePzoOP/) + +[back to table of contents](#table-of-contents) + + +### Mọi thứ ở giữa theo chiều dọc + +Không, đó không phải là ảo thuật, bạn thực sự có thể căn giữa các yếu tố theo chiều dọc.Bạn có thể làm điều này với flexbox ... + +```css +html, +body { + height: 100%; + margin: 0; +} + +body { + -webkit-align-items: center; + -ms-flex-align: center; + align-items: center; + display: -webkit-flex; + display: flex; +} +``` + +... và với Grid cũng vậy: + +```css +body { + display: grid; + height: 100vh; + margin: 0; + place-items: center center; +} +``` + + +Muốn căn giữa một cái gì đó khác? Theo chiều dọc,chiều ngang ... bất cứ điều gì, mọi lúc, mọi nơi? CSS-Tricks có [a nice write-up](https://css-tricks.com/centering-css-complete-guide/) để làm được tất cả những điều đó. + +#### [Demo](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) + +[back to table of contents](#table-of-contents) + + +### Danh sách được phân tách bằng dấu phẩy + +Làm cho các mục trong danh sách trông giống như một danh sách thực, được phân tách bằng dấu phẩy: + +```css +ul > li:not(:last-child)::after { + content: ","; +} +``` + +Dùng `:not()` pseudo-class và không có dấu phẩy nào sẽ được thêm vào mục cuối cùng. + +**Note:** Mẹo này có thể không lý tưởng cho khả năng tiếp cận, đặc biệt là trình đọc màn hình.Và sao chép / dán từ trình duyệt không hoạt động với nội dung do CSS tạo.Khi làm hãy thận trọng. + +[back to table of contents](#table-of-contents) + + +### Chọn items sử dụng Negative `nth-child` + +Sử dụng phủ định `nth-child` trong CSS để chọn các mục từ 1 đến n. + +```css +li { + display: none; +} + +/* select items 1 through 3 and display them */ +li:nth-child(-n+3) { + display: block; +} +``` + +Hoặc,bạn đã biết một chút về [dùng `:not()`](#use-not-to-applyunapply-borders-on-navigation), thử: + +```css +/* select all items except the first 3 and display them */ +li:not(:nth-child(-n+3)) { + display: block; +} +``` + +#### [Demo](http://codepen.io/AllThingsSmitty/pen/WxjKZp) + +[back to table of contents](#table-of-contents) + + +### Dùng SVG cho Icons + +Không có lý do gì để không sử dụng SVG cho các biểu tượng: + +```css +.logo { + background: url("logo.svg"); +} +``` + +SVG tỉ lệ tốt cho tất cả các loại độ phân giải và được hỗ trợ trong tất cả các trình duyệt [back to IE9](http://caniuse.com/#search=svg). Loại bỏ các tệp .png, .jpg hoặc .gif-jif-whatev của bạn + +**Note:** Nếu bạn có các nút chỉ có biểu tượng SVG cho người dùng bị cận và SVG không tải được, điều này sẽ giúp duy trì khả năng truy cập: + +```css +.no-svg .icon-only::after { + content: attr(aria-label); +} +``` + +[back to table of contents](#table-of-contents) + + +### Sử dụng "Lobotomized Owl" Selector + +Nó có thể có một cái tên lạ nhưng việc sử dụng bộ chọn phổ quát (`*`) với bộ chọn anh chị em kế cận (`+`) có thể cung cấp khả năng CSS mạnh mẽ: + +```css +* + * { + margin-top: 1.5em; +} +``` + +Trong ví dụ này, tất cả các phần tử trong luồng dữ liệu theo sau các phần tử khác sẽ nhận được `margin-top: 1.5em`. + +Để biết thêm về bộ chọn "lobotomized owl", hãy đọc [Heydon Pickering's post](http://alistapart.com/article/axiomatic-css-and-lobotomized-owls). + +#### [Demo](http://codepen.io/AllThingsSmitty/pen/grRvWq) + +[back to table of contents](#table-of-contents) + + +### Dùng `max-height` cho thanh trượt CSS Sliders + +Áp dụng CSS-only sliders dùng `max-height` với overflow hidden: + +```css +.slider { + max-height: 200px; + overflow-y: hidden; + width: 300px; +} + +.slider:hover { + max-height: 600px; + overflow-y: scroll; +} +``` + +Những thành phần sẽ được mở rộng bằng `max-height` khi di chuột và thanh trượt hiển thị do overflow. + +[back to table of contents](#table-of-contents) + + +### Các ô trong bảng có chiều rộng bằng nhau + +Tables có thể gây nhức đầu khi làm việc với nó. Hãy thử dùng `table-layout: fixed` để giữ cho các ô có chiều rộng bằng nhau: + +```css +.calendar { + table-layout: fixed; +} +``` + +Bố cục bảng dễ chịu + +#### [Demo](http://codepen.io/AllThingsSmitty/pen/jALALm) + +[back to table of contents](#table-of-contents) + + +### Get Rid of Margin Hacks With Flexbox + +Khi làm việc với các rãnh cột bạn có thể loại bỏ `nth-`, `first-`, và `last-child` hack dùng flexbox's bằng `space-between` thuộc tính: + +```css +.list { + display: flex; + justify-content: space-between; +} + +.list .person { + flex-basis: 23%; +} +``` + +Giờ đây, các rãnh cột luôn xuất hiện cách đều nhau + +[back to table of contents](#table-of-contents) + + +### Sử dụng thuộc tính Selectors với các liên kết trống + +Hiển thị các liên kết khi `` phần tử không có giá trị văn bản nhưng `herf` thuộc tính có một liên kết: + +```css +a[href^="http"]:empty::before { + content: attr(href); +} +``` + +Điều đó khá tiện lợi + +#### [Demo](http://codepen.io/AllThingsSmitty/pen/zBzXRx) + +[back to table of contents](#table-of-contents) + + +### Style "Default" Links + +Thêm kiểu cho các liên kết "default": + +```css +a[href]:not([class]) { + color: #008000; + text-decoration: underline; +} +``` + +Giờ đây, các liên kết được chèn qua CMS, thường không có thuộc tính `class`, sẽ có sự phân biệt mà không ảnh hưởng chung đến tầng. + +[back to table of contents](#table-of-contents) + + +### Intrinsic Ratio Boxes + +Để tạo một hộp có tỷ lệ nội tại, tất cả những gì bạn cần làm là áp dụng phần đệm trên cùng hoặc dưới cùng cho div: + +```css +.container { + height: 0; + padding-bottom: 20%; + position: relative; +} + +.container div { + border: 2px dashed #ddd; + height: 100%; + left: 0; + position: absolute; + top: 0; + width: 100%; +} +``` + +Sử dụng 20% ​​cho phần đệm làm cho chiều cao của hộp bằng 20% ​​chiều rộng của nó. Bất kể chiều rộng của khung nhìn, div con sẽ giữ nguyên tỷ lệ co của nó (100% / 20% = 5: 1). + +#### [Demo](http://codepen.io/AllThingsSmitty/pen/jALZvE) + +[back to table of contents](#table-of-contents) + + +### Hình ảnh bị vỡ + +Làm cho hình ảnh bị hỏng trở nên đẹp hơn về mặt thẩm mỹ với một chút CSS: + +```css +img { + display: block; + font-family: sans-serif; + font-weight: 300; + height: auto; + line-height: 2; + position: relative; + text-align: center; + width: 100%; +} +``` + +Bây giờ, hãy thêm các quy tắc phần tử giả để hiển thị thông báo người dùng và tham chiếu URL của hình ảnh bị hỏng: + +```css +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; +} +``` + +Tìm hiểu thêm về cách tạo kiểu cho mẫu này trong [Ire Aderinokun](https://github.com/ireade/)'s [original post](http://bitsofco.de/styling-broken-images/). + +[back to table of contents](#table-of-contents) + + +### Dùng `rem` cho toàn cục; dùng `em` cho cục bộ + +Sau khi đặt kích thước phông chữ cơ sở ở gốc (`html { font-size: 100%; }`), đặt kích thước phông chữ cho các yếu tố văn bản thành `em`: + +```css +h2 { + font-size: 2em; +} + +p { + font-size: 1em; +} +``` + +Sau đó, đặt kích thước phông chữ cho mô-đun thành `rem`: + +```css +article { + font-size: 1.25rem; +} + +aside .module { + font-size: .9rem; +} +``` + +Giờ đây, mỗi mô-đun trở nên được chia nhỏ và dễ tạo kiểu hơn, dễ bảo trì hơn và linh hoạt hơn. + +[back to table of contents](#table-of-contents) + + +### Ẩn các video tự động phát không bị tắt tiếng + +Đây là một thủ thuật tuyệt vời cho một biểu định kiểu người dùng tùy chỉnh. Tránh làm người dùng quá tải với âm thanh từ video tự động phát khi tải trang. Nếu âm thanh không bị tắt, không hiển thị video: + +```css +video[autoplay]:not([muted]) { + display: none; +} +``` + +Một lần nữa, chúng ta đang tận dụng lợi thế của việc sử dụng [`:not()`](#use-not-to-applyunapply-borders-on-navigation) pseudo-class. + +[back to table of contents](#table-of-contents) + + +### Dùng `:root` cho Flexible Type + +Kích thước phông chữ loại trong bố cục đáp ứng có thể điều chỉnh theo từng chế độ xem. Bạn có thể tính toán kích thước phông chữ dựa trên chiều cao và chiều rộng của khung nhìn bằng cách sử dụng `:root`: + +```css +:root { + font-size: calc(1vw + 1vh + .5vmin); +} +``` + +Bây giờ bạn có thể sử dụng `root em` đơn vị dựa trên giá trị được tính bằng `:root`: + +```css +body { + font: 1rem/1.6 sans-serif; +} +``` + +#### [Demo](http://codepen.io/AllThingsSmitty/pen/XKgOkR) + +[back to table of contents](#table-of-contents) + + +### Đặt `font-size` trong Form Elements để có một trải nghiệm mobile tốt hơn + +Để tránh các trình duyệt di động (iOS Safari, v.v.) phóng to các phần tử biểu mẫu HTML khi ``的下拉列表时,为了避免表单元素在移动浏览器(iOS Safari 和其它)上的缩放,加上`font-size`: ```css input[type="text"], @@ -491,9 +590,52 @@ textarea { :dancer: -[回目录](#table-of-contents) +[回目录](#目录) + + +### 使用指针事件来控制鼠标事件 + +[指针事件](https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events)允许您指定鼠标如何与其触摸的元素进行交互。 要禁用按钮上的默认指针事件,例如: + +```css +button:disabled { + opacity: .5; + pointer-events: none; +} +``` + +就这么简单。 + +[回目录](#目录) + + +### 在用作间距的换行符上设置`display: none` + +正如[Harry Roberts指出](https://twitter.com/csswizardry/status/1170835532584235008),这有助于防止CMS用户使用额外的换行符 + +```css +br + br { + display: none; +} +``` + +[回目录](#目录) + +### 使用 `:empty` 隐藏空 HTML 元素 + +如果你有空的 HTML 元素,即内容尚未由 CMS 设置或动态注入(例如:`

`)并且它会在你的布局上创建不需要的空间,使用 `:empty` 伪类隐藏布局上的元素。 + +```css +:empty { + display: none; +} +``` + +注意:请记住,带有空格的元素不会被视为空元素,例如 `

`。 + +[回目录](#目录) ### 支持情况 -这些技巧适用于最新版的 Chrome, Firefox, Safari, Opera, Edge, 以及 IE11。 +这些技巧适用于最新版的 Chrome, Firefox, Safari, 以及 Edge。 diff --git a/translations/zh-TW/README.md b/translations/zh-TW/README.md new file mode 100644 index 00000000..e52217b5 --- /dev/null +++ b/translations/zh-TW/README.md @@ -0,0 +1,608 @@ +

+ light bulb icon +

+ +# CSS 專家密技 [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) + +這裡收集了一系列 CSS 專家密技,幫助你提升 CSS 技能點數。 + +> 更多專家密技可以查看 [@sindresorhus](https://github.com/sindresorhus/) 的 [Awesome Lists](https://github.com/sindresorhus/awesome/) + +> 正體中文由 [Will 保哥](http://blog.miniasp.com/) 翻譯,歡迎造訪 [Will 保哥的技術交流中心](https://www.facebook.com/will.fans) + + +
+ +## 目錄 + +* [專家密技](#專家密技) +* [瀏覽器支援度](#瀏覽器支援度) +* [貢獻準則](../../CONTRIBUTING.md) + +## 專家密技 + +1. [使用 CSS Reset](#使用-css-reset) +1. [繼承 `box-sizing`](#繼承-box-sizing) +1. [使用 `unset` 而不是重置所有屬性](#使用-unset-而不是重置所有屬性) +1. [使用 `:not()` 選擇器來決定表單是否顯示邊框](#使用-not-選擇器來決定表單是否顯示邊框) +1. [检查字体是否在本地安装](#检查字体是否在本地安装) +1. [將 `line-height` 加入到 `body` 元素](#將-line-height-加入到-body-元素) +1. [為表單元素設定`focus`](#為表單元素設定focus) +1. [將所有元素設定垂直居中](#將所有元素設定垂直居中) +1. [逗號分隔列表](#逗號分隔列表) +1. [使用負數的 `nth-child` 來選擇元素](#使用負數的-nth-child-來選擇元素) +1. [使用 SVG 圖示](#使用-svg-圖示) +1. [使用 "貓頭鷹" 的選擇器](#使用-貓頭鷹-選擇器) +1. [使用 `max-height` 來建立純 CSS 的捲動軸](#使用-max-height-來建立純-css-的捲動軸) +1. [讓表格中每個儲存格維持等寬](#讓表格中每個儲存格維持等寬) +1. [利用 Flexbox 去除多餘的 Margin 技巧](#利用-flexbox-去除多餘的-margin-技巧) +1. [利用屬性選擇器填滿空白連結的文字內容](#利用屬性選擇器填滿空白連結的文字內容) +1. [幫沒有類別的連結設定一個預設樣式](#幫沒有類別的連結設定一個預設樣式) +1. [等比例的方塊](#等比例的方塊) +1. [為破圖定義樣式](#為破圖定義樣式) +1. [用 `rem` 來調整全域大小;用 `em` 來調整區域大小](#用-rem-來調整全域大小用-em-來調整區域大小) +1. [隱藏沒有靜音並設定自動播放的影片](#隱藏沒有靜音並設定自動播放的影片) +1. [使用 `:root` 選擇器來設定彈性的字體大小](#使用-root-選擇器來設定彈性的字體大小) +1. [為了更好的行動體驗來設定表單元素的 `font-size`](#為了更好的行動體驗來設定表單元素的-font-size) +1. [使用指標事件來控制滑鼠事件](#使用指標事件來控制滑鼠事件) +1. [在用作間距的換行符上設置`display: none`](#在用作間距的換行符上設置display-none) + + +### 使用 CSS Reset + +CSS Reset 可以幫你在不同的瀏覽器上維持一致的樣式風格。你可以使用像 [Normalize](http://necolas.github.io/normalize.css/) 這類的 CSS Reset 套件,或使用更簡潔的 CSS Reset 方法: + +```css +*, +*::before, +*::after { + box-sizing: border-box; + margin: 0; + padding: 0; +} +``` + +現在元素的 margin 和 padding 已重設,且 `box-sizing` 可以讓你透過 CSS Box Model 管理版面配置。 + +#### [示範](http://codepen.io/AllThingsSmitty/pen/kkrkLL) + +注意:如果你接著套用 [繼承 `box-sizing`](#繼承-box-sizing) 這個技巧, 你或許不需要在你的 CSS Reset 中加入 `box-sizing` 屬性。 + +[回到目錄](#table-of-contents) + +### 繼承 `box-sizing` + +讓 `box-sizing` 屬性自動從 `html` 元素繼承下來 : + +```css +html { + box-sizing: border-box; +} + +*, +*::before, +*::after { + box-sizing: inherit; +} +``` + +如此一來,你就很容易的在其他外掛或元件裡改變 `box-sizing` 的值。 + +#### [示範](https://css-tricks.com/inheriting-box-sizing-probably-slightly-better-best-practice/) + +[回到目錄](#table-of-contents) + +### 使用 `unset` 而不是重置所有屬性 + +當重置元素的屬性時,並不需要重置元素中每個屬性: + +```css +button { + background: none; + border: none; + color: inherit; + font: inherit; + outline: none; + padding: 0; +} +``` + +你可以用 `all` 來代表元素中所有的樣式屬性。 將該值設定為 `unset` 意味著將元素中所有樣式屬性回復到預設值: + +```css +button { + all: unset; +} +``` + +[回到目錄](#table-of-contents) + +### 使用 `:not()` 選擇器來決定表單是否顯示邊框 + +假設你用以下樣式先替元素新增邊框 + +```css +/* 新增邊框 */ +.nav li { + border-right: 1px solid #666; +} +``` + +然後在最後一個元素去除邊框 + +```css +/* 去掉邊框 */ +.nav li:last-child { + border-right: none; +} +``` + +不過你可以改用 `:not()` 偽類別 (pseudo-class) 來做到完全相同的效果: + +```css +.nav li:not(:last-child) { + border-right: 1px solid #666; +} +``` + +CSS選擇器以人類描述它的方式定義邊界。 + +#### [示範](http://codepen.io/AllThingsSmitty/pen/LkymvO) + +[回到目錄](#table-of-contents) + + +### 检查字体是否在本地安装 + +您可以在远程获取字体之前检查是否在本地安装了字体,这也是一个很好的性能提示。 + +```css +@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; +} +``` + +亚当·阿盖尔(Adam Argyle)的帽子技巧,分享了这个技巧和[例子](https://codepen.io/argyleink/pen/VwYJpgR). + +[回到目錄](#table-of-contents) + + +### 將 `line-height` 加入到 `body` 元素 + +你不必為分別為每一個 `

`、`` 元素加入 `line-height` 樣式,相反的,你應該直接新增到 `body` 元素: + +```css +body { + line-height: 1.5; +} +``` + +所有的文字元素預設就會繼承 `body` 的樣式。 + +#### [示範](http://codepen.io/AllThingsSmitty/pen/VjbdYd) + +[回到目錄](#table-of-contents) + + +### 為表單元素設定`focus` + +視力正常的鍵盤使用者依靠焦點來確認鍵盤事件在頁面中的位置。使表單元素的焦點脫穎而出,然後與瀏覽器的預設實作保持一致: + +```css +a:focus, +button:focus, +input:focus, +select:focus, +textarea:focus { + box-shadow: none; + outline: #000 dotted 2px; + outline-offset: .05em; +} +``` + +#### [Demo](https://codepen.io/AllThingsSmitty/pen/ePzoOP/) + +[回到目錄](#table-of-contents) + + +### 將所有元素設定垂直居中 + +不!這絕不是黑魔法,這真的可以將所有元素設定垂直居中: + +```css +html, +body { + height: 100%; + margin: 0; +} + +body { + -webkit-align-items: center; + -ms-flex-align: center; + align-items: center; + display: -webkit-flex; + display: flex; +} +``` + +...還有 CSS Grid: + +```css +body { + display: grid; + height: 100vh; + margin: 0; + place-items: center center; +} +``` + +還想居中排版其他的東西?垂直居中、水平居中、... 任何事、任何時間、任何地點?CSS-Tricks [有篇不錯的文章](https://css-tricks.com/centering-css-complete-guide/) 提到了各種居中排版的技巧。 + +#### [示範](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) + +[回到目錄](#table-of-contents) + +### 逗號分隔列表 + +使列表的每項都由逗號分隔: + +```css +ul > li:not(:last-child)::after { + content: ','; +} +``` + +列表中最後一項不用加逗號,所以可以使用 `:not()` 偽類別 (pseudo-class) 。 + +**注意:**這一技巧對於無障礙網頁,特別是螢幕閱讀器而言,並不理想。而且預設要複製貼網頁內容時,並不會包含 CSS 動態產生的內容,這點必須特別注意。 + +[回到目錄](#table-of-contents) + +### 使用負數的 `nth-child` 來選擇元素 + +使用負數的 `nth-child` 可以選擇 1 至 n 個元素。 + +```css +li { + display: none; +} + +/* 選擇第 1 至第 3 個元素並顯示出來 */ +li:nth-child(-n+3) { + display: block; +} +``` + +或者,你已經知道 [使用 `:not()` 選擇器來決定表單是否顯示邊框](#使用-not-選擇器來決定表單是否顯示邊框) 這個技巧,你可以試試: + +```css +/* 選擇除了前 3 個之外的所有項目,並顯示出來 */ +li:not(:nth-child(-n + 3)) { + display: none; +} +``` + +就是這麼簡單! + +#### [示範](http://codepen.io/AllThingsSmitty/pen/WxjKZp) + +[回到目錄](#table-of-contents) + +### 使用 SVG 圖示 + +沒有理由不使用 SVG 圖示: + +```css +.logo { + background: url('logo.svg'); +} +``` + +SVG 在所有解析度下都可以良好縮放,並且支援 IE9 之後的所有瀏覽器,丟棄你的 .png, .jpg, 或 .gif 檔案! + +**注意:** 如果你有一個只用 SVG 圖示的按鈕,只給看的見的人來點選。當 SVG 無法載入的時候,以下樣式可以幫助你維持網頁的可及性(Accessibility): + +```css +.no-svg .icon-only::after { + content: attr(aria-label); +} +``` + +[回到目錄](#table-of-contents) + +### 使用 "貓頭鷹" 選擇器 + +這個名字 "Lobotomized Owl" (貓頭鷹) 大家可能比較陌生,不過如果你將 通用選擇器 (`*`) 和 相鄰兄弟選擇器 (`+`) 一起使用的話,將可帶來極大效益: + +```css +* + * { + margin-top: 1.5em; +} +``` + +在此範例中,在檔案中所有的元素,只要緊接著其他元素,就會套用一個 `margin-top: 1.5em` 樣式。 + +更多 "貓頭鷹" (Lobotomized Owl) 選擇器,可參考 *A List Apart* 上面關於 [Heydon Pickering 的文章](http://alistapart.com/article/axiomatic-css-and-lobotomized-owls) + +#### [示範](http://codepen.io/AllThingsSmitty/pen/grRvWq) + +[回到目錄](#table-of-contents) + +### 使用 `max-height` 來建立純 CSS 的捲動軸 + +你可以透過 `max-height` 與 `overflow-y: hidden` 來實作出 CSS-only 的捲動軸: + +```css +.slider { + max-height: 200px; + overflow-y: hidden; + width: 300px; +} + +.slider:hover { + max-height: 600px; + overflow-y: scroll; +} +``` + +當滑鼠移到 `.slider` 的元素時,元素的內容如果過多,最大高度只會擴展到 `max-height` 的值,而且會自動顯示捲動軸。 + +[回到目錄](#table-of-contents) + +### 讓表格中每個儲存格維持等寬 + +表格中要維持每一格都等寬是一件痛苦的事,所以你應該嘗試用 `table-layout: fixed` 來讓所有儲存格維持等寬: + +```css +.calendar { + table-layout: fixed; +} +``` + +這才是無痛的 Table 版面配置。 + +#### [示範](http://codepen.io/AllThingsSmitty/pen/jALALm) + +[回到目錄](#table-of-contents) + +### 利用 Flexbox 去除多餘的 Margin 技巧 + +排版的時候,為了設計出每一欄的間隙 (gutters),一般都會用到像是 `nth-`、`first-` 和 `last-child` 的技巧,來去除頭尾多餘的間隙,不如使用 Flexbox 的 `space-between` 屬性: + +```css +.list { + display: flex; + justify-content: space-between; +} + +.list .person { + flex-basis: 23%; +} +``` + +現在,每一欄之間的間隙將會平均分佈。 + +[回到目錄](#table-of-contents) + +### 利用屬性選擇器填滿空白連結的文字內容 + +當 `` 元素沒有文字內容,但有 `href` 屬性的時候,可以這樣做: + +```css +a[href^='http']:empty::before { + content: attr(href); +} +``` + +這真的非常方便。 + +#### [示範](http://codepen.io/AllThingsSmitty/pen/zBzXRx) + +[回到目錄](#table-of-contents) + +### 幫沒有類別的連結設定一個預設樣式 + +幫沒有套用 class 的超連結設定一個預設樣式: + +```css +a[href]:not([class]) { + color: #008000; + text-decoration: underline; +} +``` + +使用者透過後台 CMS 系統插入的超連結通常沒有 `class` 屬性,以上樣式可以針對這些超連結進行設定,且不會影響其它樣式定義。 + +[回到目錄](#table-of-contents) + +### 等比例的方塊 + +要建立一個固定比例的方塊 (Box),你需要的就是將 `padding-top` 或 `padding-bottom` 設定到 div 元素: + +```css +.container { + height: 0; + padding-bottom: 20%; + position: relative; +} + +.container div { + border: 2px dashed #ddd; + height: 100%; + left: 0; + position: absolute; + top: 0; + width: 100%; +} +``` + +在 `padding-bottom` 設定 `20%` 意味著各個 div 方塊的高度等同於 20% 的寬度。無論 Viewport 現在的寬度多少,子元素的 div 將維持其寬高比(100% / 20% = 5:1)。 + +#### [示範](http://codepen.io/AllThingsSmitty/pen/jALZvE) + +[回到目錄](#table-of-contents) + +### 為破圖定義樣式 + +只要一點 CSS 就可以美化所有破圖: + +```css +img { + display: block; + font-family: sans-serif; + font-weight: 300; + height: auto; + line-height: 2; + position: relative; + text-align: center; + width: 100%; +} +``` + +接著新增一個 偽元素規則 (pseudo-elements rules) 來顯示使用者訊息,以及這張破圖的 URL 參考: + +```css +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; +} +``` + +想學習更多這類樣式技巧,可以參考 [Ire Aderinokun](https://github.com/ireade/) 的 [原始文章](http://bitsofco.de/styling-broken-images/)。 + +[回到目錄](#table-of-contents) + +### 用 `rem` 來調整全域大小;用 `em` 來調整區域大小 + +在根元素設定基礎字體大小後 (`html { font-size: 100%; }`), 使用 `em` 設定文字元素的字體大小: + +```css +h2 { + font-size: 2em; +} + +p { + font-size: 1em; +} +``` + +然後設定模組的字體大小為 `rem`: + +```css +article { + font-size: 1.25rem; +} + +aside .module { + font-size: 0.9rem; +} +``` + +現在,每個模組變得獨立,更容易、靈活的樣式便於維護。 + +[回到目錄](#table-of-contents) + +### 隱藏沒有靜音並設定自動播放的影片 + +當你在一個可以自訂樣式的後台環境設定網站樣式時,這是一個不錯的小技巧。畢竟自動撥放影片是蠻惱人的,這個技巧可以幫助你避免影片在沒有靜音的情況下自動撥放。 + +```css +video[autoplay]:not([muted]) { + display: none; +} +``` + +你看,我們再次利用了 [`:not()`](#使用-not-選擇器來決定表單是否顯示邊框) 偽類別 (pseudo-class) 的優勢。 + +[回到目錄](#table-of-contents) + +### 使用 `:root` 選擇器來設定彈性的字體大小 + +在響應式版面(responsive layout)中,字體大小通常需要根據不同的 Viewport (畫面大小) 進行調整。你可以根據 `:root` 所定義的 Viewport 高度與寬度來調整字體大小: + +```css +:root { + font-size: calc(1vw + 1vh + 0.5vmin); +} +``` + +現在你便能使用依 `:root` 字級為基準的 `rem` 單位了。 + +```css +body { + font: 1rem/1.6 sans-serif; +} +``` + +#### [示範](http://codepen.io/AllThingsSmitty/pen/XKgOkR) + +[回到目錄](#table-of-contents) + +### 為了更好的行動體驗來設定表單元素的 `font-size` + +為了避免使用者在行動瀏覽器 (iOS Safari, 等等)點擊 `