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 b6ad0460..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`](https://github.com/AllThingsSmitty/css-protips/tree/master/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 8b41c7d4..514038b3 100644 --- a/README.md +++ b/README.md @@ -1,29 +1,32 @@ -

- 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) @@ -32,22 +35,27 @@ A collection of tips to help take your CSS skills pro. 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. You can use a CSS reset library like [Normalize](http://necolas.github.io/normalize.css/), _et al._, or you can use a more simplified reset approach: +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; @@ -56,12 +64,12 @@ CSS resets help enforce style consistency across different browsers with a clean Now elements will be stripped of margins and padding, and `box-sizing` lets you manage layouts with the CSS box model. -#### [Demo](http://codepen.io/AllThingsSmitty/pen/kkrkLL) - -**Note:** 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. +#### [Demo](https://codepen.io/AllThingsSmitty/pen/kkrkLL) -[back to table of contents](#table-of-contents) +> [!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` @@ -72,15 +80,43 @@ html { box-sizing: border-box; } -*, *::before, *::after { +*, +*::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) +#### [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 @@ -110,12 +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"); +} -#### [Demo](http://codepen.io/AllThingsSmitty/pen/LkymvO) +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` @@ -129,38 +185,80 @@ body { This way textual elements can inherit from `body` easily. -#### [Demo](http://codepen.io/AllThingsSmitty/pen/VjbdYd) +#### [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: -[back to table of contents](#table-of-contents) +```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; } ``` -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. +...and also with CSS Grid: -**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. +```css +body { + display: grid; + height: 100vh; + place-items: center; +} +``` + +> [!TIP] +> Want to center something else? Vertically, horizontally...anything, anytime, anywhere? CSS-Tricks has [a nice write-up](https://css-tricks.com/centering-css-complete-guide/) on doing all of that. + +#### [Demo](https://codepen.io/AllThingsSmitty/pen/GqmGqZ) -#### [Demo](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) +[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 @@ -172,12 +270,12 @@ ul > li:not(:last-child)::after { } ``` -Use the `:not()` pseudo-class so no comma is 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. +Use the `:not()` pseudo-class and no comma will be added to the last item. -[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` @@ -189,7 +287,7 @@ li { } /* select items 1 through 3 and display them */ -li:nth-child(-n+3) { +li:nth-child(-n + 3) { display: block; } ``` @@ -198,17 +296,14 @@ Or, since you've already learned a little about [using `:not()`](#use-not-to-app ```css /* select all items except the first 3 and display them */ -li:not(:nth-child(-n+3)) { - display: none; +li:not(:nth-child(-n + 3)) { + display: block; } ``` -Well that was pretty easy. - -#### [Demo](http://codepen.io/AllThingsSmitty/pen/WxjKZp) - -[back to table of contents](#table-of-contents) +#### [Demo](https://codepen.io/AllThingsSmitty/pen/WxjKZp) +[Back to top](#contents) ### Use SVG for Icons @@ -220,9 +315,10 @@ 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 { @@ -230,8 +326,7 @@ SVG scales well for all resolution types and is supported in all browsers [back } ``` -[back to table of contents](#table-of-contents) - +[Back to top](#contents) ### Use the "Lobotomized Owl" Selector @@ -245,12 +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_. -#### [Demo](http://codepen.io/AllThingsSmitty/pen/grRvWq) - -[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 @@ -271,12 +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) - +[Back to top](#contents) ### 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 { @@ -286,10 +380,9 @@ Tables can be a pain to work with so try using `table-layout: fixed` to keep cel Pain-free table layouts. -#### [Demo](http://codepen.io/AllThingsSmitty/pen/jALALm) - -[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 @@ -308,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 @@ -321,43 +413,74 @@ a[href^="http"]:empty::before { } ``` -That's pretty convenient. +That's really convenient. -#### [Demo](http://codepen.io/AllThingsSmitty/pen/zBzXRx) +#### [Demo](https://codepen.io/AllThingsSmitty/pen/zBzXRx) -[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) -### Style "Default" Links +### Control Specificity Better with `:is()` -Add a style for "default" links: +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) -Use a universal selector (`*`) within an element to create a consistent vertical rhythm: +### Style "Default" Links + +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 @@ -382,10 +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). -#### [Demo](http://codepen.io/AllThingsSmitty/pen/jALZvE) - -[back to table of contents](#table-of-contents) +#### [Demo](https://codepen.io/AllThingsSmitty/pen/jALZvE) +[Back to top](#contents) ### Style Broken Images @@ -394,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; @@ -420,10 +542,10 @@ img::after { } ``` -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 @@ -447,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 @@ -468,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 @@ -477,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); } ``` @@ -489,10 +609,9 @@ body { } ``` -#### [Demo](http://codepen.io/AllThingsSmitty/pen/XKgOkR) - -[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 @@ -507,28 +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: -[back to table of contents](#table-of-contents) +```css +br + br { + display: none; +} +``` +[Back to top](#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; +} +``` -[back to table of contents](#table-of-contents) +#### [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) -* [ગુજરાતી](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) -* [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) -* [Русский](https://github.com/AllThingsSmitty/css-protips/tree/master/translations/ru-RU) -* [简体中文](https://github.com/AllThingsSmitty/css-protips/tree/master/translations/zh-CN) - -[back to table of contents](#table-of-contents) +> [!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/de-DE/Readme.md b/de-DE/Readme.md deleted file mode 100644 index 300dec33..00000000 --- a/de-DE/Readme.md +++ /dev/null @@ -1,535 +0,0 @@ -

-lampensymbol -

- -# CSS PRO Tips [! [Super] (https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) - - -Eine Sammlung von Tipps, mit denen Your CSS-Kenntnisse verbessern können. - -> Für andere tolle prüfen Hören Sie heraus [@] (sindresorhus Https://github.com/sindresorhus/)'s kuratiert Liste der Listen [Super] (https://github.com/sindresorhus/awesome/). - - -## Inhaltsverzeichnis - -* [Pro Tips] (#Pro Tips) -* [Support] (#Support) -* [Übersetzungen] (#Übersetzungen) -* [Beitrag Leitlinien] (beitragen. md) - - -## Pro Tips - -1. [Verwenden Sie einen CSS-Reset] (#use-a-css-Reset) -1. [Erben' Box-sizing"] (#Erben-box-Sizing) -1. [Benutzen': nicht bewerben () '/Entfernen Sie sterben Rahmen für sterben Navigation] (# verwenden-nicht-anwenden-anwenden-Grenzen-bei-Navigation) -1. [Füge 'line-height' zu 'Körper' hinzu] (#hinzufügen - Linie-Höhe-zu-Karosserie) -1. [Vertikal-Center Etwas] (#vertikal-Zentrum-etwas) -1. [Kommagetrennte Listen] (#comma-separated-Listen) -1. [Wählen Sie Elemente mit negativen "nth-child'] (#wählen - Einzelteile - Verwendung - negative - n-Kind) -1. [ SVG für Icons] (#verwenden - SVG-Icons) -1. [Verwenden Sie die "Lobotomisiert Eule "Selector] (#verwenden - Der-Lobotomisiert - Owl-Selector) -1. [Verwenden Sie die 'Max-height' für reine CSS-Regler] (#-max-height-für-rein-css-Schieberegler) -1. [Equal-Width Tabellenzellen] (#Höhe - Breite - Tabelle-Zellen) -1. [Loswerden Marge Hacks mit Flexbox] (#get-rid-of-margin-Hacks-mit-Flexbox) -1. [Verwenden Sie die Attribut Selektoren mit leeren Links] (#-Attribut-Selektoren-mit-leer-links) -1. [Style "Default"-Links] (#Style-default-links) -1. [Konsistente vertikale Rhythmus] (#konsequent - Vertikal - Rhythmus) -1. [Inneren Verhältnis Boxen] (#Intrinsic-Ratio-Boxen) -1. [Style gebrochen Bilder] (#Style - gebrochen - Bilder) -1. [Verwenden Sie 'rem' für globale Größe; verwenden Sie 'em' für Lokale Sizing] (#verwenden - Rem-für-global-sizing-verwenden-em-für-local-Sizing) -1. [Ausblenden Automatische Wiedergabe von Videos, die nicht stummgeschaltet sind.] (#verstecken - autoplay - Videos -, dass arent Stummgeschalteten) -1. [Verwendung": root' für Flexible Type] (#use-root-für-flexible-Typ) -1. [Set 'font-size' auf dem Formular Elemente für eine bessere mobile Erfahrung] (#set-font-size-auf-form-Elemente-für-ein-besser-mobile-Erfahrung) - - -### Verwenden eines CSS-Reset - -CSS setzt Hilfe erzwingen Stil Konsistenz über verschiedene Browser mit einem sauberen Schiefer für Stilelemente. Sie können ein CSS-reset Bibliothek wie [Normalisieren] (Http://necolas.github.io/normalize.css/),_et al_, oder Sie können eine vereinfachte reset Ansatz verwenden: - -'''css -*{ -box-sizing: border-box; -margin: 0; -padding: 0; -} -''' - -Jetzt Elemente wird entfernt der Seitenränder und Textabstand und 'box-sizing" können Sie Layouts mit Css Box Model zu verwalten. - -#### [Demo] (http://codepen.io/AllThingsSmitty/pen/kkrkLL) - -** Hinweis: ** Wenn Sie die [Erben" folgen - grössensortierung"] (#Erben-box-Sizing) Tipp unten entscheiden Sie sich möglicherweise nicht die "box-sizing" Eigenschaft in Ihrem CSS-Reset. - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### Erben' Box-sizing ' - -Lassen' Box-sizing" von "vererbt werden html': - -'''css -html- -box-sizing: border-box; -} - -*,*::*:: Nach { -box-sizing: erben; -} -''' - -Das macht es leichter zu ändern' Box-sizing" in Plugins oder andere Komponenten, nutzen andere Verhalten. - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### Verwenden': (Nicht) Anwenden/Unapply grenzt an Navigation - -anstatt an der Grenze... - -'''Css -/* Grenze */ -. nav Li { -border-right:1px Solid #666; -} -''' - -... und dann nehmen Sie das letzte Element... - -'''Css -/* entfernen Sie Grenze */ -. nav Li: Letztes - Kind { -border-right:none; -} -''' - -... Die": (Nicht) 'Pseudo-Klasse nur für die Elemente, die Sie anwenden möchten: - -'''css -. nav Li: (Nicht: Letztes - Kind) { -border-right:1px Solid #666; -} -''' - -Sicher, können Sie mit der Option '. nav Li + li' oder sogar '. nav Li:first-child~li', aber mit ': (Nicht) "Die Absicht ist klar und die CSS-Selektor definiert die Grenze die Art und Weise, wie ein Mensch es beschreiben würde. - -#### [Demo] (http://codepen.io/AllThingsSmitty/pen/LkymvO) - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -###Add 'line-height', 'Körper', die - -Sie nicht hinzufügen müssen, 'line-height', '

','', _et al_. getrennt. Stattdessen fügen Sie sie zu 'Körper': - -'''css -Body { -line-height: 1.5; -} -''' auf - -diese Weise textuelle Elemente erben können von 'Körper'. - -#### [Demo] (http://codepen.io/AllThingsSmitty/pen/VjbdYd) - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### Vertically-Center Alles, - -nein, es ist keine schwarze Magie, Sie können wirklich Zentrum Elemente vertikal: - -'''css -html, body { -Height: 100%; -margin: 0; -} - -Body{ -- webkit-Ausrichten-Reihen: Zentrum; -- ms-flex-align: center; -Ausrichten - Produkte: center; -Display: - webkit-Flex; -Anzeige: Flex; -} -''' - -Wollen in die Mitte etwas anderes? Vertikal, Horizontal... alles, jederzeit, überall? CSS-Tricks hat [ein nettes Schreiben] (Https://css-tricks.com/centering-css-complete-guide/) auf all das tun. - -** Hinweis: ** Achten Sie auf einige [buggy Verhalten] (Https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items) mit der Flex-box in IE 11. - -#### [Demo] (http://codepen.io/AllThingsSmitty/pen/GqmGqZ) - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### kommagetrennte Listen - -Liste Elemente wie ein echter, Komma-getrennte Liste Aussehen: - -'''Css -Ul > li: (Nicht: Letztes - Kind):: Nach { -content:", "; -} -''' - -verwenden, um die': (Nicht) 'Pseudo-Klasse so kein Komma auf das letzte Element hinzugefügt wird. - -**Hinweis**: Dieser Tipp ist vielleicht nicht ideal für Zugänglichkeit, speziell Screen Reader. Und copy/paste aus dem Browser nicht mit CSS-generierten Inhalten. Mit Vorsicht vorgehen. - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### wählen Sie Elemente mit negativen "nth-child ' - -negative' nth-child" in CSS zu wählen Sie die Elemente 1 bis n. - -'''Css -li { -display:none; -} - -/* wählen Sie die Optionen 1 bis 3 und Anzeige*/ -li: nth-child (-n+3) { -Display: Block; -} -''' - -oder, da Sie bereits gelernt haben, ein wenig über [Verwendung': (Nicht)'] (#-nicht-zu-applyunapply-Grenzen-auf-navigation), versuchen Sie: - -'''css -/* Alle Elemente außer den ersten 3 und angezeigt werden */ -li: (Nicht: nth-child (-n+3)) { -display:none; -} -''' - -Gut, die recht einfach war. - -#### [Demo] (http://codepen.io/AllThingsSmitty/pen/WxjKZp) - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### SVG für Icons verwenden, - -es gibt keinen Grund, nicht SVG für Symbole zu verwenden: - -'''css -. Logo { -Background: url("logo.svg"); -} -''' - -SVG-Skalen sowie für alle Auflösung und ist in allen Browsern [zurück zu IE 9] (Http://caniuse.com/#search=svg). unterstützt. So graben Sie Ihre .png, .jpg oder .gif - jif-whatev Dateien. - -**Hinweis**: Wenn Sie SVG-Symbol - nur Tasten für sehende Benutzer und der SVG nicht geladen wird, wird diese Hilfe Zugänglichkeit: - -'''css -. Nein - svg. Symbol - nur: Nach { -Inhalt: Attr (aria-Label); -} -''' - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### Die "Lobotomisiert Eule "Selector - -es eine seltsame Namen haben kann, aber mit dem universellen Selektor ("*") mit den dazugehörigen gleichgeordneten Selektor ("+") kann ein leistungsfähiges CSS-Funktionen: - -'''css -*+*{ -margin-top: 1.5Em; -} -''' - -In diesem Beispiel werden alle Elemente in der Strömung der Dokument, folgen die anderen Elemente erhalten bin 'margin-top:1.5em' bieten. - -Für weitere Informationen über die "Lobotomisiert Eule "Selector, lesen [ Heydon Pickering's Post] (Http://alistapart.com/article/axiomatic-css-and-lobotomized-owls) auf * eine Liste abgesehen*. - -#### [Demo] (http://codepen.io/AllThingsSmitty/pen/grRvWq) - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### Verwenden Sie 'max-height' für reine CSS-Schieberegler - -implementieren CSS-Slider mit 'max-height' mit Überlauf versteckt: - -'''css -. Schieberegler { -max-height: 200px; -overflow-y:hidden; -width: 300px; -} - -. Regler:hover { -max-height: 600px; -overflow-y: scroll; -} -''' - -das Element auf die 'Max-height' Wert auf schweben und der Schieberegler zeigt als Ergebnis der Überlauf wird erweitert. - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### Equal-Width Zellen der Tabelle - -Tabellen ein Schmerz sein können, so versuchen Sie es mit 'table-layout: Fixed' Zellen bei gleicher Breite zu halten: - -'''css -. Kalender { -table-layout:fixed; -} -''' - -Schmerz- tabelle Layouts. - -#### [Demo] (http://codepen.io/AllThingsSmitty/pen/jALALm) - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### Loswerden Marge Hacks mit Flexbox - -beim Arbeiten mit Spalte Dachrinnen erhalten Sie loszuwerden' n-te-', '-', und 'last-child" Hacks mit Hilfe der Flex-box Tempo - zwischen "Eigentum: - -'''css -. Liste { -Display: Flex; -rechtfertigen - Inhalt: Raum - Zwischen; -} - -. Liste. Person{ -flex-Basis: 23%; -} -''' - -Jetzt Spalte Dachrinnen erscheinen immer gleichmäßig verteilte. - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### Verwenden Sie das Attribut Selektoren mit leeren Links - -Anzeigen links Wenn die '-Element hat kein Text wert aber das 'href' Attribut hat einen Link: - -'''css- -a[href^="http"]: Leer:: Vor dem { -content: attr(href); -} -''' - -Das ist ziemlich praktisch. - -#### [Demo] (http://codepen.io/AllThingsSmitty/pen/zBzXRx) - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### Style "Default" Links - -ein Stil für "default" links hinzufügen: - -'''css- -a[href]: Nicht ([Klasse]){ -color:#008000; -text-decoration: underline; -} -''' - -Jetzt links, die über ein CMS, das nicht normalerweise ein "class"-Attribut eingefügt sind, wird eine Unterscheidung ohne generisch, die die Kaskade. - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### konsistente vertikale Rhythmus - -mit einem universellen Selektor ('*') innerhalb eines Elements eine konsistente vertikale Rhythmus zu erstellen: - -''' css -. intro > * { -margin-bottom: 1,25 rem; -} -''' - -konsistente vertikale Rhythmus bietet eine visuelle Ästhetik, die Macht Inhalt weit mehr lesbar. - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### intrinsische Verhältnis Boxen - -eine Box mit einem inneren Verhältnis zu erstellen, müssen Sie nur die obere oder untere Polsterung um ein div gelten: - -'''css- -Container { -height:0; -padding-bottom:20%; -position:relative; -} - -. div-Container { -border: 2px gestrichelte #ddd; -Height: 100%; -Left: 0; -Position: absolute; -top: 0; -width: 100%; -} -''' - -mit 20 % für die Polsterung macht die Höhe des Feldes in Höhe von 20 % der Breite. Egal, die Breite des Bildbereichs, dem Kind div wird das Seitenverhältnis (100% / 20% = 5:1) halten. - -#### [Demo] (http://codepen.io/AllThingsSmitty/pen/jALZvE) - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### Stil gebrochen Bilder - -machen kaputt Bilder mehr ästhetisch ansprechend mit ein wenig CSS: - -'''css -img { -Display: Block; -font-family:Helvetica, Arial, sans-serif; -font-weight:300; -height: auto; -line-height: 2; -Position: relative; -text-align: center; -width: 100%; -} -''' - -Jetzt pseudo-elemente Regeln hinzufügen eine Meldung für den Benutzer und URL-Referenz des gebrochenen Bild anzuzeigen: - -'''css -img::Vor dem { -content: "Es tut uns Leid, das Bild unten gebrochen ist: ("; -Display: Block; -margin-bottom: 10px; -} - -img:: Nach { -content: "url: " attr (Src)")"; -Display: Block; -font-size: 12px; -} -''' - -erfahren Sie mehr über Styling für dieses Muster in [Ire (https://github.com/ireade/)'s Aderinokun] [Original post] (http://bitsofco.de/styling-broken-images/). - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### Verwenden Sie m'für Globale Größe; verwenden Sie 'em' für Lokale Dimensionierung - -nach Einstellung der Schriftgröße an der Wurzel ('html {font-size: 100%; }"), stellen Sie die Schriftgröße für textuelle Elemente zu 'em': - -'''css -h2 { -font-size: 2em; -} - -p { -font-size:1em; -} -''', - -dann die font-size für Module zu 'rem': - -''' css- -Artikel { -font-size: 1,25 rem; -} - -beiseite. Modul { -font-size: 9 rem; -} -''' - -jetzt jedes Modul wird abgeschottet und leichter Stil, wartungsfreundlicher und flexibel. - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### ausblenden Automatische Wiedergabe von Videos, die nicht - -Dies ist ein toller Trick für ein benutzerdefiniertes Stylesheet stummgeschaltet sind. Vermeiden Sie die Überlastung einer Benutzer mit Klang aus einem Video, das Vollbildmodus wiedergegeben, wenn die Seite geladen wird. Wenn der Ton nicht stumm geschaltet ist, nicht das Video: - -'''css -Video [Wiedergabe]: Nicht ([Stumm]) { -display:none; -} -''' - -noch einmal, wir Vorteil der Verwendung der [': (Nicht)'] (#-nicht-zu-applyunapply-Grenzen-auf-navigation) pseudo-Klasse zeigen. - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### Verwenden': root' für Flexible type - -Der Typ Schriftgröße in einem reaktionsschnellen Layout sollte in der Lage sein, mit jedem Bildfenster einzustellen. Sie können die Schriftgröße auf dem Bildfenster, um Höhe und Breite Verwendung': root' berechnet werden: - -'''css -: root { -font-size: Calc (1 vw + 1 vh +. 5 Vmin); -} -''' - -können Sie die 'root em' auf den Wert von "Berechnet benutzen: root': - -'''css -Body{ -font: - - - - - - - - - - - - -css1 rem/1.6 sans-serif;}'''#### [Demo] (http://codepen.io/AllThingsSmitty/pen/XKgOkR) [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) ### Stellen Sie 'font-size' auf dem Formular Elemente für eine bessere mobile Erfahrung mit mobilen Browsern (iOS-Safari,_et al_.) von Zoom auf HTML-Formular elemente Wenn ein '`-Dropdown betätigt wird, ergänze `font-size` zu der Regel des Selektors: + +```css +input[type="text"], +input[type="number"], +select, +textarea { + font-size: 16px; +} +``` + +:dancer: + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +### Benutze `Pointer`-Events um Mausereignisse zu kontrollieren + +[Pointer-Events](https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events) erlauben es dir zu spezifizieren wie die Maus mit dem Element interagiert sobald sie es berührt. Um beispielsweise das standardgemäß eingestellte Pointer-Event – beispielsweise bei einer Button-Schaltfläche – abzuschalten: + +```css +button:disabled { + opacity: .5; + pointer-events: none; +} +``` + +So einfach ist das. + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +### Stellen Sie bei Zeilenumbrüchen, die als Abstand verwendet werden, `display: none` ein + +Wie [Harry Roberts hervorhob](https://twitter.com/csswizardry/status/1170835532584235008), kann dies dazu beitragen, dass CMS-Benutzer keine zusätzlichen Zeilenumbrüche als Abstand verwenden: + +```css +br + br { + display: none; +} +``` + +[zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) + + +## Unterstützung + +Aktuelle Versionen von Chrome, Firefox, Safari, und Edge. \ No newline at end of file diff --git a/translations/du-NL/Readme.md b/translations/du-NL/Readme.md deleted file mode 100644 index 2d073d97..00000000 --- a/translations/du-NL/Readme.md +++ /dev/null @@ -1,535 +0,0 @@ -

-lampensymbol -

- -# CSS PRO Tips [! [Super] (https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) - - -Eine Sammlung von Tipps, mit denen Your CSS-Kenntnisse verbessern können. - -> Für andere tolle prüfen Hören Sie heraus [@] (sindresorhus Https://github.com/sindresorhus/)'s kuratiert Liste der Listen [Super] (https://github.com/sindresorhus/awesome/). - - -## Inhaltsverzeichnis - -* [Pro Tips] (#Pro Tips) -* [Support] (#Support) -* [Übersetzungen] (#Übersetzungen) -* [Beitrag Leitlinien] (beitragen. md) - - -## Pro Tips - -1. [Verwenden Sie einen CSS-Reset] (#use-a-css-Reset) -1. [Erben' Box-sizing"] (#Erben-box-Sizing) -1. [Benutzen': nicht bewerben () '/Entfernen Sie sterben Rahmen für sterben Navigation] (# verwenden-nicht-anwenden-anwenden-Grenzen-bei-Navigation) -1. [Füge 'line-height' zu 'Körper' hinzu] (#hinzufügen - Linie-Höhe-zu-Karosserie) -1. [Vertikal-Center Etwas] (#vertikal-Zentrum-etwas) -1. [Kommagetrennte Listen] (#comma-separated-Listen) -1. [Wählen Sie Elemente mit negativen "nth-child'] (#wählen - Einzelteile - Verwendung - negative - n-Kind) -1. [ SVG für Icons] (#verwenden - SVG-Icons) -1. [Verwenden Sie die "Lobotomisiert Eule "Selector] (#verwenden - Der-Lobotomisiert - Owl-Selector) -1. [Verwenden Sie die 'Max-height' für reine CSS-Regler] (#-max-height-für-rein-css-Schieberegler) -1. [Equal-Width Tabellenzellen] (#Höhe - Breite - Tabelle-Zellen) -1. [Loswerden Marge Hacks mit Flexbox] (#get-rid-of-margin-Hacks-mit-Flexbox) -1. [Verwenden Sie die Attribut Selektoren mit leeren Links] (#-Attribut-Selektoren-mit-leer-links) -1. [Style "Default"-Links] (#Style-default-links) -1. [Konsistente vertikale Rhythmus] (#konsequent - Vertikal - Rhythmus) -1. [Inneren Verhältnis Boxen] (#Intrinsic-Ratio-Boxen) -1. [Style gebrochen Bilder] (#Style - gebrochen - Bilder) -1. [Verwenden Sie 'rem' für globale Größe; verwenden Sie 'em' für Lokale Sizing] (#verwenden - Rem-für-global-sizing-verwenden-em-für-local-Sizing) -1. [Ausblenden Automatische Wiedergabe von Videos, die nicht stummgeschaltet sind.] (#verstecken - autoplay - Videos -, dass arent Stummgeschalteten) -1. [Verwendung": root' für Flexible Type] (#use-root-für-flexible-Typ) -1. [Set 'font-size' auf dem Formular Elemente für eine bessere mobile Erfahrung] (#set-font-size-auf-form-Elemente-für-ein-besser-mobile-Erfahrung) - - -### Verwenden eines CSS-Reset - -CSS setzt Hilfe erzwingen Stil Konsistenz über verschiedene Browser mit einem sauberen Schiefer für Stilelemente. Sie können ein CSS-reset Bibliothek wie [Normalisieren] (Http://necolas.github.io/normalize.css/),_et al_, oder Sie können eine vereinfachte reset Ansatz verwenden: - -'''css -*{ -box-sizing: border-box; -margin: 0; -padding: 0; -} -''' - -Jetzt Elemente wird entfernt der Seitenränder und Textabstand und 'box-sizing" können Sie Layouts mit Css Box Model zu verwalten. - -#### [Demo] (http://codepen.io/AllThingsSmitty/pen/kkrkLL) - -** Hinweis: ** Wenn Sie die [Erben" folgen - grössensortierung"] (#Erben-box-Sizing) Tipp unten entscheiden Sie sich möglicherweise nicht die "box-sizing" Eigenschaft in Ihrem CSS-Reset. - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### Erben' Box-sizing ' - -Lassen' Box-sizing" von "vererbt werden html': - -'''css -html- -box-sizing: border-box; -} - -*,*::*:: Nach { -box-sizing: erben; -} -''' - -Das macht es leichter zu ändern' Box-sizing" in Plugins oder andere Komponenten, nutzen andere Verhalten. - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### Verwenden': (Nicht) Anwenden/Unapply grenzt an Navigation - -anstatt an der Grenze... - -'''Css -/* Grenze */ -. nav Li { -border-right:1px Solid #666; -} -''' - -... und dann nehmen Sie das letzte Element... - -'''Css -/* entfernen Sie Grenze */ -. nav Li: Letztes - Kind { -border-right:none; -} -''' - -... Die": (Nicht) 'Pseudo-Klasse nur für die Elemente, die Sie anwenden möchten: - -'''css -. nav Li: (Nicht: Letztes - Kind) { -border-right:1px Solid #666; -} -''' - -Sicher, können Sie mit der Option '. nav Li + li' oder sogar '. nav Li:first-child~li', aber mit ': (Nicht) "Die Absicht ist klar und die CSS-Selektor definiert die Grenze die Art und Weise, wie ein Mensch es beschreiben würde. - -#### [Demo] (http://codepen.io/AllThingsSmitty/pen/LkymvO) - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -###Add 'line-height', 'Körper', die - -Sie nicht hinzufügen müssen, 'line-height', '

','', _et al_. getrennt. Stattdessen fügen Sie sie zu 'Körper': - -'''css -Body { -line-height: 1.5; -} -''' auf - -diese Weise textuelle Elemente erben können von 'Körper'. - -#### [Demo] (http://codepen.io/AllThingsSmitty/pen/VjbdYd) - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### Vertically-Center Alles, - -nein, es ist keine schwarze Magie, Sie können wirklich Zentrum Elemente vertikal: - -'''css -html, body { -Height: 100%; -margin: 0; -} - -Body{ -- webkit-Ausrichten-Reihen: Zentrum; -- ms-flex-align: center; -Ausrichten - Produkte: center; -Display: - webkit-Flex; -Anzeige: Flex; -} -''' - -Wollen in die Mitte etwas anderes? Vertikal, Horizontal... alles, jederzeit, überall? CSS-Tricks hat [ein nettes Schreiben] (Https://css-tricks.com/centering-css-complete-guide/) auf all das tun. - -** Hinweis: ** Achten Sie auf einige [buggy Verhalten] (Https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items) mit der Flex-box in IE 11. - -#### [Demo] (http://codepen.io/AllThingsSmitty/pen/GqmGqZ) - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### kommagetrennte Listen - -Liste Elemente wie ein echter, Komma-getrennte Liste Aussehen: - -'''Css -Ul > li: (Nicht: Letztes - Kind):: Nach { -content:", "; -} -''' - -verwenden, um die': (Nicht) 'Pseudo-Klasse so kein Komma auf das letzte Element hinzugefügt wird. - -**Hinweis**: Dieser Tipp ist vielleicht nicht ideal für Zugänglichkeit, speziell Screen Reader. Und copy/paste aus dem Browser nicht mit CSS-generierten Inhalten. Mit Vorsicht vorgehen. - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### wählen Sie Elemente mit negativen "nth-child ' - -negative' nth-child" in CSS zu wählen Sie die Elemente 1 bis n. - -'''Css -li { -display:none; -} - -/* wählen Sie die Optionen 1 bis 3 und Anzeige*/ -li: nth-child (-n+3) { -Display: Block; -} -''' - -oder, da Sie bereits gelernt haben, ein wenig über [Verwendung': (Nicht)'] (#-nicht-zu-applyunapply-Grenzen-auf-navigation), versuchen Sie: - -'''css -/* Alle Elemente außer den ersten 3 und angezeigt werden */ -li: (Nicht: nth-child (-n+3)) { -display:none; -} -''' - -Gut, die recht einfach war. - -#### [Demo] (http://codepen.io/AllThingsSmitty/pen/WxjKZp) - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### SVG für Icons verwenden, - -es gibt keinen Grund, nicht SVG für Symbole zu verwenden: - -'''css -. Logo { -Background: url("logo.svg"); -} -''' - -SVG-Skalen sowie für alle Auflösung und ist in allen Browsern [zurück zu IE 9] (Http://caniuse.com/#search=svg). unterstützt. So graben Sie Ihre .png, .jpg oder .gif - jif-whatev Dateien. - -**Hinweis**: Wenn Sie SVG-Symbol - nur Tasten für sehende Benutzer und der SVG nicht geladen wird, wird diese Hilfe Zugänglichkeit: - -'''css -. Nein - svg. Symbol - nur: Nach { -Inhalt: Attr (aria-Label); -} -''' - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### Die "Lobotomisiert Eule "Selector - -es eine seltsame Namen haben kann, aber mit dem universellen Selektor ("*") mit den dazugehörigen gleichgeordneten Selektor ("+") kann ein leistungsfähiges CSS-Funktionen: - -'''css -*+*{ -margin-top: 1.5Em; -} -''' - -In diesem Beispiel werden alle Elemente in der Strömung der Dokument, folgen die anderen Elemente erhalten bin 'margin-top:1.5em' bieten. - -Für weitere Informationen über die "Lobotomisiert Eule "Selector, lesen [ Heydon Pickering's Post] (Http://alistapart.com/article/axiomatic-css-and-lobotomized-owls) auf * eine Liste abgesehen*. - -#### [Demo] (http://codepen.io/AllThingsSmitty/pen/grRvWq) - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### Verwenden Sie 'max-height' für reine CSS-Schieberegler - -implementieren CSS-Slider mit 'max-height' mit Überlauf versteckt: - -'''css -. Schieberegler { -max-height: 200px; -overflow-y:hidden; -width: 300px; -} - -. Regler:hover { -max-height: 600px; -overflow-y: scroll; -} -''' - -das Element auf die 'Max-height' Wert auf schweben und der Schieberegler zeigt als Ergebnis der Überlauf wird erweitert. - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### Equal-Width Zellen der Tabelle - -Tabellen ein Schmerz sein können, so versuchen Sie es mit 'table-layout: Fixed' Zellen bei gleicher Breite zu halten: - -'''css -. Kalender { -table-layout:fixed; -} -''' - -Schmerz- tabelle Layouts. - -#### [Demo] (http://codepen.io/AllThingsSmitty/pen/jALALm) - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### Loswerden Marge Hacks mit Flexbox - -beim Arbeiten mit Spalte Dachrinnen erhalten Sie loszuwerden' n-te-', '-', und 'last-child" Hacks mit Hilfe der Flex-box Tempo - zwischen "Eigentum: - -'''css -. Liste { -Display: Flex; -rechtfertigen - Inhalt: Raum - Zwischen; -} - -. Liste. Person{ -flex-Basis: 23%; -} -''' - -Jetzt Spalte Dachrinnen erscheinen immer gleichmäßig verteilte. - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### Verwenden Sie das Attribut Selektoren mit leeren Links - -Anzeigen links Wenn die '-Element hat kein Text wert aber das 'href' Attribut hat einen Link: - -'''css- -a[href^="http"]: Leer:: Vor dem { -content: attr(href); -} -''' - -Das ist ziemlich praktisch. - -#### [Demo] (http://codepen.io/AllThingsSmitty/pen/zBzXRx) - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### Style "Default" Links - -ein Stil für "default" links hinzufügen: - -'''css- -a[href]: Nicht ([Klasse]){ -color:#008000; -text-decoration: underline; -} -''' - -Jetzt links, die über ein CMS, das nicht normalerweise ein "class"-Attribut eingefügt sind, wird eine Unterscheidung ohne generisch, die die Kaskade. - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### konsistente vertikale Rhythmus - -mit einem universellen Selektor ('*') innerhalb eines Elements eine konsistente vertikale Rhythmus zu erstellen: - -''' css -. intro > * { -margin-bottom: 1,25 rem; -} -''' - -konsistente vertikale Rhythmus bietet eine visuelle Ästhetik, die Macht Inhalt weit mehr lesbar. - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### intrinsische Verhältnis Boxen - -eine Box mit einem inneren Verhältnis zu erstellen, müssen Sie nur die obere oder untere Polsterung um ein div gelten: - -'''css- -Container { -height:0; -padding-bottom:20%; -position:relative; -} - -. div-Container { -border: 2px gestrichelte #ddd; -Height: 100%; -Left: 0; -Position: absolute; -top: 0; -width: 100%; -} -''' - -mit 20 % für die Polsterung macht die Höhe des Feldes in Höhe von 20 % der Breite. Egal, die Breite des Bildbereichs, dem Kind div wird das Seitenverhältnis (100% / 20% = 5:1) halten. - -#### [Demo] (http://codepen.io/AllThingsSmitty/pen/jALZvE) - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### Stil gebrochen Bilder - -machen kaputt Bilder mehr ästhetisch ansprechend mit ein wenig CSS: - -'''css -img { -Display: Block; -font-family:Helvetica, Arial, sans-serif; -font-weight:300; -height: auto; -line-height: 2; -Position: relative; -text-align: center; -width: 100%; -} -''' - -Jetzt pseudo-elemente Regeln hinzufügen eine Meldung für den Benutzer und URL-Referenz des gebrochenen Bild anzuzeigen: - -'''css -img::Vor dem { -content: "Es tut uns Leid, das Bild unten gebrochen ist: ("; -Display: Block; -margin-bottom: 10px; -} - -img:: Nach { -content: "url: " attr (Src)")"; -Display: Block; -font-size: 12px; -} -''' - -erfahren Sie mehr über Styling für dieses Muster in [Ire (https://github.com/ireade/)'s Aderinokun] [Original post] (http://bitsofco.de/styling-broken-images/). - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### Verwenden Sie m'für Globale Größe; verwenden Sie 'em' für Lokale Dimensionierung - -nach Einstellung der Schriftgröße an der Wurzel ('html {font-size: 100%; }"), stellen Sie die Schriftgröße für textuelle Elemente zu 'em': - -'''css -h2 { -font-size: 2em; -} - -p { -font-size:1em; -} -''', - -dann die font-size für Module zu 'rem': - -''' css- -Artikel { -font-size: 1,25 rem; -} - -beiseite. Modul { -font-size: 9 rem; -} -''' - -jetzt jedes Modul wird abgeschottet und leichter Stil, wartungsfreundlicher und flexibel. - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### ausblenden Automatische Wiedergabe von Videos, die nicht - -Dies ist ein toller Trick für ein benutzerdefiniertes Stylesheet stummgeschaltet sind. Vermeiden Sie die Überlastung einer Benutzer mit Klang aus einem Video, das Vollbildmodus wiedergegeben, wenn die Seite geladen wird. Wenn der Ton nicht stumm geschaltet ist, nicht das Video: - -'''css -Video [Wiedergabe]: Nicht ([Stumm]) { -display:none; -} -''' - -noch einmal, wir Vorteil der Verwendung der [': (Nicht)'] (#-nicht-zu-applyunapply-Grenzen-auf-navigation) pseudo-Klasse zeigen. - - [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) - - -### Verwenden': root' für Flexible type - -Der Typ Schriftgröße in einem reaktionsschnellen Layout sollte in der Lage sein, mit jedem Bildfenster einzustellen. Sie können die Schriftgröße auf dem Bildfenster, um Höhe und Breite Verwendung': root' berechnet werden: - -'''css -: root { -font-size: Calc (1 vw + 1 vh +. 5 Vmin); -} -''' - -können Sie die 'root em' auf den Wert von "Berechnet benutzen: root': - -'''css -Body{ -font: - - - - - - - - - - - - -css1 rem/1.6 sans-serif;}'''#### [Demo] (http://codepen.io/AllThingsSmitty/pen/XKgOkR) [Zurück zum Inhaltsverzeichnis] (#Table-of-Contents) ### Stellen Sie 'font-size' auf dem Formular Elemente für eine bessere mobile Erfahrung mit mobilen Browsern (iOS-Safari,_et al_.) von Zoom auf HTML-Formular elemente Wenn ein '` 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 index a285ba1a..f1d37d96 100644 --- a/translations/gu-IND/README.md +++ b/translations/gu-IND/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) @@ -19,9 +19,12 @@ ## પ્રોપ્સ 1. [એક સીએસએસ રીસેટ વાપરો](#વાપરવ-a-css-રીસેટ) -1. [વારસો `box-sizing`](#વારસો-box-sizing) +1. [વારસો `box-sizing`](#વારસો-box-sizing)F +1. [બધા ગુણધર્મોને ફરીથી સેટ કરવાને બદલે 'અનસેટ' નો ઉપયોગ કરો](#બધા-ગુણધર્મોને-ફરીથી-સેટ-કરવાને-બદલે-અનસેટ-નો-ઉપયોગ-કરો) 1. [વાપરવ `:not()` અરજી / અનપ્પેલી કરવા માટે નેવિગેશન પર બોર્ડર્સ](#વાપરવ-not-અરજી--અનપ્પેલી-કરવા-માટે-નેવિગેશન-પર-બોર્ડર્સ) -1. [ઉમેરો `line-height` તરફ `body`](#ઍડ-line-height-થી-body) +1. [સ્થાનિક રીતે ફોન્ટ ઇન્સ્ટોલ કરેલું છે કે નહીં તે તપાસો](#સ્થાનિક-રીતે-ફોન્ટ-ઇન્સ્ટોલ-કરેલું-છે-કે-નહીં-તે-તપાસો) +1. [ઉમેરો `line-height` તરફ `body`](#ઉમેર-line-height-તરફ-body) +1. [ફોર્મ તત્વો માટે 'ધ્યાન કેન્દ્રિત કરો' સેટ કરો](#ફોર્મ-તત્વો-માટે-ધ્યાન-કેન્દ્રિત-કરો-સેટ-કરો) 1. [વર્ટિકલ-કેન્દ્ર કંઈપણ](#ઊભું-કેન્દ્ર-કંઈપણ) 1. [કોમા-વિભાજિત સૂચિ](#કોમા-વિભાજિત-સૂચિ) 1. [નકારાત્મક મદદથી વસ્તુઓ પસંદ કરો `nth-child`](#નકારાત્મક-મદદથી-વસ્તુઓ-પસંદ-કરો-nth-child) @@ -32,13 +35,14 @@ 1. [છુટકારો મેળવવા માર્જિન હેક્સ સાથે Flexbox](#છુટકારો-મેળવવા-માર્જિન-હેક્સ-સાથે-flexbox) 1. [વાપરવ એટ્રીબ્યુટ પસંદગીકારો સાથે ખાલી કડીઓ](#વાપરવ-એટ્રીબ્યુટ-પસંદગીકારો-સાથે-ખાલી-કડીઓ) 1. [પ્રકાર "Default" કડીઓ](#પ્રકાર-default-કડીઓ) -1. [સુસંગત વર્ટિકલ રિધમ](#સુસંગત-વર્ટિકલ-રિધમ) 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 રીસેટ @@ -46,7 +50,9 @@ સીએસએસ રીસેટ્સ સ્ટાઇલ ઘટકો માટે સ્વચ્છ સ્લેટ સાથે વિવિધ બ્રાઉઝર્સમાં સ્ટાઇલ સુસંગતતાને અમલમાં મૂકવા માટે મદદ કરે છે. તમે જેમ કે CSS રીસેટ લાઇબ્રેરીનો ઉપયોગ કરી શકો છો [Normalize](http://necolas.github.io/normalize.css/), _et al._, અથવા તમે વધુ સરળ રીસેટ અભિગમનો ઉપયોગ કરી શકો છો: ```css -* { +*, +*::before, +*::after { box-sizing: border-box; margin: 0; padding: 0; @@ -55,7 +61,7 @@ હવે તત્વો માર્જિન અને પેડિંગની છીનવી લેવામાં આવશે, અને `box-sizing` તમે સીએસએસ બોક્સ મોડેલ સાથે લેઆઉટ મેનેજ કરી શકો છો. -#### [Demo](http://codepen.io/AllThingsSmitty/pen/kkrkLL) +#### [પ્રદર્શન](http://codepen.io/AllThingsSmitty/pen/kkrkLL) **નોટ:** જો તમે અનુસરશો તો [Inherit `box-sizing`](#inherit-box-sizing) નીચે ટીપ તમે નીચેની શામેલ ન કરવાનું પસંદ કરી શકો છો `box-sizing` મિલકત માં તમારા CSS રીસેટ . @@ -71,13 +77,45 @@ html { box-sizing: border-box; } -*, *::before, *::after { +*, +*::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` અને` અનસેટ` શોર્ટહેન્ડ સપોર્ટેડ નથી. + [સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) @@ -109,9 +147,35 @@ html { } ``` -ખાતરી કરો, તમે ઉપયોગ કરી શકો `.nav li + li` અથવા તો `.nav li:first-child ~ li`, પરંતુ સાથે `:not()` ઉદ્દેશ ખૂબ જ સ્પષ્ટ છે અને CSS પસંદગીકાર સરહદને તે રીતે વ્યાખ્યાયિત કરે છે. +CSS પસંદગીકાર સીમાને વ્યાખ્યાયિત કરે છે કે જે રીતે મનુષ્ય તેનું વર્ણન કરશે. -#### [Demo](http://codepen.io/AllThingsSmitty/pen/LkymvO) +#### [પ્રદર્શન](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). [સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) @@ -128,7 +192,28 @@ body { આ માર્ગ textual તત્વો શકવું બોલાવે થી `body` સરળતાથી. -#### [Demo](http://codepen.io/AllThingsSmitty/pen/VjbdYd) +#### [પ્રદર્શન](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/) [સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) @@ -138,7 +223,8 @@ body { ના, તે કાળા જાદુ નથી, તમે ખરેખર ઊભી તત્વોને કેન્દ્રિત કરી શકો છો: ```css -html, body { +html, +body { height: 100%; margin: 0; } @@ -150,13 +236,21 @@ body { display: -webkit-flex; display: flex; } -``` +`` +...અને CSS ગ્રીડ સાથે પણ: -કેન્દ્ર માંગો છો કંઈક બીજું? વર્ટિકલ, આડા...કંઈપણ, કોઈપણ સમયે, ગમે ત્યાં? CSS-Tricks has [a nice write-up](https://css-tricks.com/centering-css-complete-guide/) on કરવાનું બધા કે. +```css +body { + display: grid; + height: 100vh; + margin: 0; + place-items: center center; +} +```` -**નોટ:** જુઓ કેટલાક માટે [buggy behavior](https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items) સાથે flexbox માં IE11. +કેન્દ્ર માંગો છો કંઈક બીજું? વર્ટિકલ, આડા...કંઈપણ, કોઈપણ સમયે, ગમે ત્યાં? CSS-Tricks has [a nice write-up](https://css-tricks.com/centering-css-complete-guide/) on કરવાનું બધા કે. -#### [Demo](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) +#### [પ્રદર્શન](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) [સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) @@ -204,7 +298,7 @@ li:not(:nth-child(-n+3)) { વેલ તે ખૂબ સરળ હતું. -#### [Demo](http://codepen.io/AllThingsSmitty/pen/WxjKZp) +#### [પ્રદર્શન](http://codepen.io/AllThingsSmitty/pen/WxjKZp) [સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) @@ -246,7 +340,7 @@ The SVG scale is good for all resolution types and it is supported in all browse વધુ માટે "lobotomized owl" પસંદગીકાર, વાંચવું [Heydon Pickering's post](http://alistapart.com/article/axiomatic-css-and-lobotomized-owls) on *A List Apart*. -#### [Demo](http://codepen.io/AllThingsSmitty/pen/grRvWq) +#### [પ્રદર્શન](http://codepen.io/AllThingsSmitty/pen/grRvWq) [સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) @@ -285,7 +379,7 @@ The SVG scale is good for all resolution types and it is supported in all browse પેઇન-મુક્ત કોષ્ટક લેઆઉટ. -#### [Demo](http://codepen.io/AllThingsSmitty/pen/jALALm) +#### [પ્રદર્શન](http://codepen.io/AllThingsSmitty/pen/jALALm) [સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) @@ -322,7 +416,7 @@ a[href^="http"]:empty::before { તે ખૂબ અનુકૂળ છે -#### [Demo](http://codepen.io/AllThingsSmitty/pen/zBzXRx) +#### [પ્રદર્શન](http://codepen.io/AllThingsSmitty/pen/zBzXRx) [સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) @@ -343,21 +437,6 @@ a[href]:not([class]) { [સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) -### સુસંગત વર્ટિકલ રિધમ - -સાર્વત્રિક પસંદગીકારનો ઉપયોગ કરો (`*`) એક તત્વ અંદર સતત ઊભા લય બનાવવા માટે: - -```css -.intro > * { - margin-bottom: 1.25rem; -} -``` - -સતત વ્રેટકલ લય દૃશ્ય એકંદર પૂરી પાડે છે જે સામગ્રીને વધુ વાંચવા માટે બનાવે છે. - -[સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) - - ### આંતરિક ગુણોત્તર બૉક્સીસ સ્વભાવિક રેશિયો સાથે બૉક્સ બનાવવા માટે, તમારે ફક્ત ટોચ અથવા તળિયે ગાદીને DIV પર લાગુ કરવાની જરૂર છે: @@ -381,7 +460,7 @@ a[href]:not([class]) { પેડિંગ માટે 20% નો ઉપયોગ કરીને તેના પહોળાઈના 20% જેટલા બૉક્સની ઊંચાઇને બનાવે છે. કોઈ વ્યૂપોર્ટની પહોળાઇ, બાળક ડિવ તેના પાસા રેશિયો રાખશે (100% / 20% = 5:1). -#### [Demo](http://codepen.io/AllThingsSmitty/pen/jALZvE) +#### [પ્રદર્શન](http://codepen.io/AllThingsSmitty/pen/jALZvE) [સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) @@ -393,7 +472,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; @@ -488,7 +567,7 @@ body { } ``` -#### [Demo](http://codepen.io/AllThingsSmitty/pen/XKgOkR) +#### [પ્રદર્શન](http://codepen.io/AllThingsSmitty/pen/XKgOkR) [સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) @@ -511,8 +590,37 @@ textarea { [સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) +### માઉસ ઇવેન્ટ્સ નિયંત્રણ કરવા માટે પોઇન્ટર ઇવેન્ટ્સનો ઉપયોગ કરો + +[પોઇન્ટર ઇવેન્ટ્સ](https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events) તમને સ્પષ્ટ કરવા માટે પરવાનગી આપે છે કે માઉસ કેવી રીતે તૃપ્તિ સાથે સંપર્ક કરે છે. બટનો પર ડિફૉલ્ટ પોઇન્ટર ઇવેન્ટને અક્ષમ કરવા માટે, ઉદાહરણ તરીકે: + +```css +button:disabled { + opacity: .5; + pointer-events: none; +} +``` + +તે સરળ છે. + +[સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) + + +### અંતર `display: none` તરીકે વપરાયેલ લાઇન બ્રેક્સ પર સેટ કરો + +[હેરી રોબર્ટ્સે નિર્દેશ કર્યો](https://twitter.com/csswizardry/status/1170835532584235008), આ સીએમએસ વપરાશકર્તાઓને અંતર માટે વધારાના લાઇન બ્રેકનો ઉપયોગ કરવાથી અટકાવી શકે છે: + +```css +br + br { + display: none; +} +``` + +[સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) + + ## આધાર -વર્તમાન આવૃત્તિઓ of Chrome, Firefox, Safari, Opera, Edge, અને IE11. +વર્તમાન આવૃત્તિઓ of Chrome, Firefox, Safari, અને Edge. [સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) diff --git a/translations/it-IT/README.md b/translations/it-IT/README.md index 4af744a6..49ef54e5 100644 --- a/translations/it-IT/README.md +++ b/translations/it-IT/README.md @@ -1,5 +1,5 @@

- light bulb icon + light bulb icon

# CSS suggerimenti per esperti [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) @@ -18,37 +18,41 @@ Una collezione di dritte per aiutarti a migliorare le tue capacità con CSS. ## Suggerimenti per esperti -1. [Utilizzare un reset CSS](#use-a-css-reset) -1. [Eredita il `box-sizing`](#inherit-box-sizing) -1. [Usa `:not()` per applicare/rimuovere i bordi su elementi di navigazione](#use-not-to-applyunapply-borders-on-navigation) -1. [Aggiungi `line-height` al `body`](#add-line-height-to-body) -1. [Centra verticalmente qualsiasi cosa](#vertically-center-anything) -1. [Liste separate da virgola](#comma-separated-lists) -1. [Seleziona un elemento usando gli `nth-child` negativi](#select-items-using-negative-nth-child) -1. [Usa SVG per le icone](#use-svg-for-icons) -1. [Usa il selettore detto "Lobotomized Owl"](#use-the-lobotomized-owl-selector) -1. [Usa `max-height` per slider fatti solo con CSS](#use-max-height-for-pure-css-sliders) -1. [Celle di tabella con larghezza uguale](#equal-width-table-cells) -1. [Sbarazzati degli hack sui margini grazie a Flexbox](#get-rid-of-margin-hacks-with-flexbox) -1. [Usa il selettore d'attributo con i link senza testo](#use-attribute-selectors-with-empty-links) -1. [Styling dei link di "Default"](#style-default-links) -1. [Mantieni un ritmo verticale coerente](#consistent-vertical-rhythm) -1. [Box con proporzioni intrinseche](#intrinsic-ratio-boxes) -1. [Styling delle immagini non scaricate](#style-broken-images) -1. [Usa `rem` per le grandezze globali; usa `em` per le dimensioni locali](#use-rem-for-global-sizing-use-em-for-local-sizing) -1. [Nascondi i video in riproduzione automatica che non sono silenziati](#hide-autoplay-videos-that-arent-muted) -1. [Usa `:root` per caratteri flessibili](#use-root-for-flexible-type) -1. [Imposta il `font-size` sugli elementi dei form per una migliore esperienza da mobile](#set-font-size-on-form-elements-for-a-better-mobile-experience) - - -
+1. [Utilizzare un reset CSS](#utilizzare-un-reset-css) +1. [Eredita il `box-sizing`](#eredita-il-box-sizing) +1. [Usa `unset` invece di Reimposta tutte le proprietà](#usa-unset-invece-di-reimposta-tutte-le-proprietà) +1. [Usa `:not()` per applicare/rimuovere-i-bordi-su-elementi-di-navigazione](#usa-not-per-applicarerimuovere-i-bordi-su-elementi-di-navigazione) +1. [Controlla se il font è installato localmente](#controlla-se-il-font-è-installato-localmente) +1. [Aggiungi `line-height` al `body`](#aggiungi-line-height-al-body) +1. [Imposta `:focus` per gli elementi del modulo](#imposta-focus-per-gli-elementi-del-modulo) +1. [Centra verticalmente qualsiasi cosa](#centra-verticalmente-qualsiasi-cosa) +1. [Liste separate da virgola](#liste-separate-da-virgola) +1. [Seleziona un elemento usando gli `nth-child` negativi](#seleziona-un-elemento-usando-gli-nth-child-negativi) +1. [Usa SVG per le icone](#usa-svg-per-le-icone) +1. [Usa il selettore detto "Lobotomized Owl"](#usa-il-selettore-detto-"lobotomized-owl") +1. [Usa `max-height` per slider fatti solo con CSS](#usa-max-height-per-slider-fatti-solo-con-css) +1. [Celle di tabella con larghezza uguale](#celle-di-tabella-con-larghezza-uguale) +1. [Sbarazzati degli hack sui margini grazie a Flexbox](#sbarazzati-degli-hack-sui-margini-grazie-a-flexbox) +1. [Usa il selettore d'attributo con i link senza testo](#usa-il-selettore-d'attributo-con-i-link-senza-testo) +1. [Styling dei link di "Default"](#styling-dei-link-di-"default") +1. [Box con proporzioni intrinseche](#box-con-proporzioni-intrinseche) +1. [Styling delle immagini non scaricate](#styling-delle-immagini-non-scaricate) +1. [Usa `rem` per le grandezze globali; usa `em` per le dimensioni locali](#usa-rem-per-le-grandezze-globali;-usa-em-per-le-dimensioni-locali) +1. [Nascondi i video in riproduzione automatica che non sono silenziati](#nascondi-i-video-in-riproduzione-automatica-che-non-sono-silenziati) +1. [Usa `:root` per caratteri flessibili](#usa-:root-per-caratteri-flessibili) +1. [Imposta il `font-size` sugli elementi dei form per una migliore esperienza da mobile](#imposta-il-font-size-sugli-elementi-dei-form-per-una-migliore-esperienza-da-mobile) +1. [Utilizzare gli eventi puntatore per controllare gli eventi del mouse](#utilizzare-gli-eventi-puntatore-per-controllare-gli-eventi-del-mouse) +1. [Imposta `display: none` su Line Breaks usati come Spaziatura](#imposta-display:-none-su-line-breaks-usati-come-spaziatura) + ### Utilizzare un reset CSS reset CSS aiutare a far rispettare lo stile coerenza tra diversi browser da zero per gli elementi stilistici. È possibile utilizzare libreria di reset CSS come [Normalize](http://necolas.github.io/normalize.css/), et al, oppure è possibile utilizzare un approccio più semplificato di ripristino.: ```css -* { +*, +*::before, +*::after { box-sizing: border-box; margin: 0; padding: 0; @@ -64,8 +68,6 @@ Ora elementi saranno spogliati di margini e padding, e `box-sizing` consente di [torna al sommario](#sommario) -
- ### Eredita il `box-sizing` Eredita il `box-sizing` dall'elemento `html`: @@ -75,17 +77,45 @@ html { box-sizing: border-box; } -*, *::before, *::after { +*, +*::before, +*::after { box-sizing: inherit; } ``` In questo modo diventa più facile cambiare `box-sizing` in plugin o altri componenti che ne sfruttano un altro. +#### [Dimostrazione](https://css-tricks.com/inheriting-box-sizing-probably-slightly-better-best-practice/) + [torna al sommario](#sommario) -
+### Usa `unset` invece di Reimposta tutte le proprietà + +Quando si ripristinano le proprietà di un elemento, non è necessario reimpostare ogni singola proprietà: + +```css +button { + background: none; + border: none; + color: inherit; + font: inherit; + outline: none; + padding: 0; +} +``` + +Puoi specificare tutte le proprietà di un elemento usando la stenografia `all`. L'impostazione del valore su `unset` modifica le proprietà di un elemento ai valori iniziali: + +```css +button { + all: unset; +} +``` + +[torna al sommario](#sommario) + ### Usa `:not()` per applicare/rimuovere i bordi su elementi di navigazione @@ -115,18 +145,43 @@ Invece di impostare il bordo... } ``` -Certo, puoi usare `.nav li + li` o anche `.nav li:first-child ~ li`, ma con `:not()` l'intento è molto chiaro e il selettore CSS definisce il bordo nel modo in cui un essere umano lo descriverebbe. +Il selettore CSS definisce il confine nel modo in cui un essere umano lo descrive. #### [Dimostrazione](http://codepen.io/AllThingsSmitty/pen/LkymvO) [torna al sommario](#sommario) -
+### Controlla se il font è installato localmente + +Puoi verificare se un font è installato localmente prima di recuperarlo da remoto, il che è anche un buon suggerimento per le prestazioni. + +```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; +} +``` + +Punta del cappello ad Adam Argyle per aver condiviso questo prototipo e questa [dimostrazione](https://codepen.io/argyleink/pen/VwYJpgR). + +[torna al sommario](#sommario) + ### Aggiungi `line-height` al `body` -You don't need to add `line-height` to each `

`, ``, _et al_. separately. Instead, add it to `body`: +Non è necessario aggiungere `line-height` a ogni `

`,``, _et al_. separatamente. Invece, aggiungilo a `body`: + ```css body { @@ -141,14 +196,34 @@ In questo modo gli elementi di testo possono ereditare facilmente da `body`. [torna al sommario](#sommario) -

+### Imposta `:focus` per gli elementi del modulo + +Gli utenti con tastiera a vista si affidano alla messa a fuoco per determinare dove vanno gli eventi della tastiera nella pagina. Fai attenzione agli elementi del modulo che si distinguono e coerenti rispetto all'implementazione predefinita del browser: + +```css +a:focus, +button:focus, +input:focus, +select:focus, +textarea:focus { + box-shadow: none; + outline: #000 dotted 2px; + outline-offset: .05em; +} +``` + +#### [Dimostrazione](https://codepen.io/AllThingsSmitty/pen/ePzoOP/) + +[torna al sommario](#sommario) + ### Centra verticalmente qualsiasi cosa No, non è magia nera. Puoi veramente centrare gli elementi verticalmente: ```css -html, body { +html, +body { height: 100%; margin: 0; } @@ -162,17 +237,24 @@ body { } ``` -Vuoi centrare qualcos'altro? In verticale, in orizzontale... qualsiasi cosa, in qualsiasi momento ovunque? Su CSS-Tricks trovi [un ottimo articolo](https://css-tricks.com/centering-css-complete-guide/) a riguardo. +...e anche con CSS Grid: -**Nota bene:** si verificano dei [comportamenti anomali](https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items) con flexbox e IE11. +```css +body { + display: grid; + height: 100vh; + margin: 0; + place-items: center center; +} +``` + +Vuoi centrare qualcos'altro? In verticale, in orizzontale... qualsiasi cosa, in qualsiasi momento ovunque? Su CSS-Tricks trovi [un ottimo articolo](https://css-tricks.com/centering-css-complete-guide/) a riguardo. #### [Dimostrazione](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) [torna al sommario](#sommario) -
- ### Liste separate da virgola Visualizza gli elementi di una lista come fossero una vera lista con le virgole: @@ -190,8 +272,6 @@ Usa la pseudo classe `:not()` in modo da non aggiungere la virgola all'ultimo el [torna al sommario](#sommario) -
- ### Seleziona un elemento usando gli `nth-child` negativi Usa gli `nth-child` negativi di CSS per selezionare gli elementi da 1 a n. @@ -223,8 +303,6 @@ Beh... era abbastanza facile. [torna al sommario](#sommario) -
- ### Usa SVG per le icone Non c'è ragione per non usare SVG per le icone: @@ -248,8 +326,6 @@ SVG scala molto bene a tutti i tipi di risoluzione ed è supportata in tutti i b [torna al sommario](#sommario) -
- ### Usa il selettore detto "Lobotomized Owl" Sebbene il suo nome sia un po' strano, l'uso del selettore universale (`*`) insieme al selettore del fratello adiacente (`+`) può fornire una potenzialità CSS molto potente: @@ -269,8 +345,6 @@ Per saperne di più sul selettore detto "lobotomized owl", leggi [l'articolo di [torna al sommario](#sommario) -
- ### Usa `max-height` per slider fatti solo con CSS Realizza slider fatti solo con CSS usando `max-height` con overflow hidden: @@ -293,8 +367,6 @@ L'elemento si espande al valore `max-height` all'hover e lo slider diventa visib [torna al sommario](#sommario) -
- ### Celle di tabella con larghezza uguale Lavorare con le tabelle può dare il tormento, perciò prova a usare `table-layout: fixed` per avere celle di larghezza uguale: @@ -312,8 +384,6 @@ Layout con le tabelle e senza tormento. [torna al sommario](#sommario) -
- ### Sbarazzati degli hack sui margini grazie a Flexbox Quando lavori con gli spazi tra colonne puoi sbarazzarti di `nth-`, `first-` e `last-child` usando la proprietà `space-between` di flexbox: @@ -334,8 +404,6 @@ Ora le colonne avranno sempre una spaziatura uniforme. [torna al sommario](#sommario) - - ### Usa il selettore d'attributo con i link senza testo Quando l'elemento `
` non ha testo al suo interno ma l'attributo `href` ha un link, lo mostra: @@ -353,8 +421,6 @@ Decisamente comodo. [torna al sommario](#sommario) - - ### Styling dei link di "Default" Aggiunge uno stile per i link "default": @@ -371,25 +437,6 @@ Ora i link inseriti mediante un CMS, che solitamente non hanno un attributo `cla [torna al sommario](#sommario) -
- -### Mantieni un ritmo verticale coerente - -Fai uso di un selettore universale (`*`) all'interno di un elemento per creare un ritmo verticale coerente: - -```css -.intro > * { - margin-bottom: 1.25rem; -} -``` - -Un ritmo verticale coerente procura un'estetica visuale che favorisce la leggibilità del conenuto. - -[torna al sommario](#sommario) - - -
- ### Box con proporzioni intrinseche Per creare un contenitore con proporzioni intrinseche tutto ciò che devi fare è applicare a un div del `padding` superiore o inferiore: @@ -418,8 +465,6 @@ Uare un `padding` del 20% rende l'altezza del contenitore pari al 20% della sua [torna al sommario](#sommario) -
- ### Styling delle immagini non scaricate Rendi le immagini non scaricate più piacevoli esteticamente con un po' di CSS: @@ -427,7 +472,7 @@ Rendi le immagini non scaricate più piacevoli esteticamente con un po' di CSS: ```css img { display: block; - font-family: Helvetica, Arial, sans-serif; + font-family: sans-serif; font-weight: 300; height: auto; line-height: 2; @@ -458,8 +503,6 @@ Ulteriori informazioni sullo styling secondo questo pattern nell'[articolo](http [torna al sommario](#sommario) -
- ### Usa `rem` per le grandezze globali; usa `em` per le dimensioni locali Dopo avere impostato la dimensione di base del font sull'elemento root (`html { font-size: 100%; }`), imposta la dimensione del font per gli elementi testuali con `em`: @@ -491,8 +534,6 @@ A questo punto ogni modulo diventa compartimentalizzato, più facile da modellar [torna al sommario](#sommario) -
- ### Nascondi i video in riproduzione automatica che non sono silenziati Questo è un fantastico trucchetto per un foglio di stile personalizzato per un utente. Evita di sovraccaricare un utente col suono di un video che parte in riproduzione automatica quando la pagina viene caricata. Se il suono non è disabilitato non mostrare il video: @@ -508,8 +549,6 @@ Ancora una volta stiamo sfruttando la pseudo classe [`:not()`](#use-not-to-apply [torna al sommario](#sommario) -
- ### Usa `:root` per caratteri flessibili In un layout responsive la grandezza del carattere dovrebbe essere in grado di adattarsi a ogni risoluzione. Puoi calcolare la dimensione del font basandoti sull'altezza e sulla larghezza della finestra usando `:root`: @@ -533,8 +572,6 @@ body { [torna al sommario](#sommario) -
- ### Imposta il `font-size` sugli elementi dei form per una migliore esperienza da mobile Per evitare lo zoom sugli elementi dei form dai browser mobile (iOS Safari, _et al_.) quando si tocca una ``드롭다운을 탭 할 때 HTML 폼 요소가 줌 인 되는 것을 피하기 위해 `font-size` 의 선택자 룰을 추가한다. + +```css +input[type="text"], +input[type="number"], +select, +textarea { + font-size: 16px; +} +``` + +:dancer: + +[목차로 돌아가기](#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` 을 설정하십시오. + +[Harry Roberts가 지적한대로](https://twitter.com/csswizardry/status/1170835532584235008) CMS 사용자가 추가 줄 바꿈을 사용하여 간격을 두지 못하게 할 수 있습니다. + +```css +br + br { + display: none; +} +``` + +[목차로 돌아가기](#table-of-contents) + + +
+ +## 지원 + +최신 버전의 Chrome, Firefox, Safari, Edge에서 지원됩니다.. + +[목차로 돌아가기](#table-of-contents) + + diff --git a/translations/pl-PL/README.md b/translations/pl-PL/README.md index 7bd8d190..c2e9788d 100644 --- a/translations/pl-PL/README.md +++ b/translations/pl-PL/README.md @@ -1,49 +1,52 @@

- light bulb icon + light bulb icon

-# wskazówki CSS [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) +# Wskazówki CSS [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) -Zbiór porad, które pomogą zdobyć umiejętności CSS. - -> W potrzebue innych wspaniałych list sprawdź zobacz [@sindresorhus](https://github.com/sindresorhus/)'s lista [zaufanych list](https://github.com/sindresorhus/awesome/). +Zbiór porad, które pomogą Ci rozwinąć zawansowane umiejętności CSS. +> Sprawdż takze inne wspaniałe listy [@sindresorhus](https://github.com/sindresorhus/) z [zaufanych list](https://github.com/sindresorhus/awesome/). ## Powrót do spisu treści -* [Wskazowki](#Wskazowki) +* [Wskazówki](#Wskazowki) * [Wsparcie](#Wsparcie) -* [Wskazówki dotyczące wkładu](../../CONTRIBUTING.md) +* [Wskazówki dotyczące kontrybucji do tego projektu](../../CONTRIBUTING.md) -## Wskazowki +## Wskazówki 1. [Użyj resetowania CSS](#użyj-resetowania-css) -1. [Odziedzicz `box-sizing`](#odziedzicz-box-sizing) -1. [Użyj `:not()` aby zastosować / anulować ograniczenia w nawigacji](#use-not-to-applyunapply-borders-on-navigation) -1. [Dodaj `line-height` do `body`](#dodaj-wysokość-linii-do-treści) -1. [Przesuń cokoliweg pionowo](#przesuwanie-w-pionie) +1. [Dziedziczenie `box-sizing`](#dziedziczenie-box-sizing) +1. [Użyj `unset` zamiast resetowania wszystkich ustawień](#użyj-unset-zamiast-resetowania-wszystkich-ustawień) +1. [Użyj `:not()` aby dodać/usunąć obramownie nawigacji](#użyj-not-aby-dodaćusunąć-obramownie-nawigacji) +1. [Sprawdź, czy czcionka jest zainstalowana lokalnie](#sprawdź,-czy-czcionka-jest-zainstalowana-lokalnie) +1. [Dodaj `line-height` do `body`](#dodaj-line-height-do-body) +1. [Ustaw `:focus` dla elementów formularza](#ustaw-:focus-dla-form-elements) +1. [Przesuń cokolwiek pionowo](#przesuwanie-w-pionie) 1. [Listy rozdziele przecinkami](#listy-podzielone-przecinkami) -1. [Wybierz przedmioty za pomocą negatywnego `nth-child`](#wybierz-przedmioty-za-pomocą-nth-child) +1. [Wybierz elementy za pomocą negatywnego `nth-child`](#wybierz-przedmioty-za-pomocą-nth-child) 1. [Użyj SVG dla ikon ](#użyj-svg-dla-ikon) 1. [Użyj selektora "Lobotomized Owl"](#użyj-selektora-lobotomized-owl) 1. [Użyj `max-height` dla suwaków Pure CSS](#użyjmax-height-dla-suwaków-pure-csss) -1. [Równoważne komórki tabeli](#równoważne-komórki-tabeli) -1. [Pozbądź się margin za pomocą Flexbox](#pozbądź-się-marginesów-za-pomocą-flexbox) +1. [Komórki tabeli o równej-szerokości](#równoważne-komórki-tabeli) +1. [Pozbądź się marginesów za pomocą Flexbox](#pozbądź-się-marginesów-za-pomocą-flexbox) 1. [Użyj selektorów atrybutów z pustymi linkami](#użyj-selektorów-atrybutów-z-pustymi-linkami) -1. [Linki w stylu "Default" ](#stylizuj-domyślne-linki) -1. [Spójny pionowy rytm](#spójny-pionowy-rytm) -1. [Indywidualne pola wyników](#indywidualne-pola-wyników) -1. [Wystylizuj Uszkodzone Obrazy](#wystylizuj-uszkodzone-obrazy) -1. [Użyj `rem` for Global Sizing; Użyj `em` for Local Sizing](#użyj-rem-dla-global-sizing-użyj-em-dla-local-sizing) +1. [Stylizuj domyślne linki](#stylizuj-domyślne-linki) +1. [Wewnętrzne proporcje bloków](#wewnętrzne-proporcje-bloków) +1. [Wystylizuj uszkodzone obrazy](#wystylizuj-uszkodzone-obrazy) +1. [Użyj `rem` dla ustawień globalnych rozmiarow i `em` do ustawień localnych](#użyj-rem-dla-ustawień-globalnych-rozmiarow-i-em-do-ustawień-localnych) 1. [Ukryj filmy z autoodtwarzaniem, które nie są wyciszone](#ukryj-filmy-z-autoodtwarzaniem-które-nie-są-wyciszone) -1. [Użyj `:root` for Flexible Type](#użyj-root-tryp-elastyczny) -1. [Ustaw `font-size` w elementach formularza, aby uzyskać lepsze wrażenia z urządzenia mobilnego](#ustaw-font-size-w-elementach-formularza-aby-uzyskać-lepsze-wrażenia-z-urządzenia-mobilnego) +1. [Użyj `:root` dla elastycznych typów](#użyj-`:root`-dla-elastycznych-typów) +1. [Ustaw rozmiar czcionki w elementach formularza](#ustaw-rozmiar-czcionki-w-elementach-formularza) +1. [Użyj zdarzeń wskaźnika do sterowania zdarzeniami myszy](#użyj-zdarzeń-wskaźnika-do-sterowania-zdarzeniami-myszy) +1. [Ustaw `display: none` na Podziały linii używane jako odstępy](#ustaw-display-none-na-podziały-linii-używane-jako-odstępy) ### Użyj resetowania CSS -Resetowanie CSS wspomaga wymuszać spójność stylu w różnych przeglądarkach z czystym konturem dla elementów stylizacyjnych. Kożystanie z biblioteki resetującej CSS, takiej jak Normalize i innie, lub użycie bardzije uproszczonego sposobu resetowania: +Reset ustawień CSS umośliwia wymuszenie spójność stylu w różnych przeglądarkach z czystym konturem dla elementów stylizacyjnych. Możesz wykorzystać jedną bibliotek resetującej ustawienia CSS np. [Normalize](http://necolas.github.io/normalize.css/) lub użyć uproszczonego sposobu resetowania: ```css * { @@ -53,16 +56,16 @@ Resetowanie CSS wspomaga wymuszać spójność stylu w różnych przeglądarkach } ``` -Elementy zostaną pozbawione marginesów i dopełnienia, a `box-sizing` pozwala zarządzać układami za pomocą modelu pudełkowego CSS +Elementy zostaną pozbawione marginesów i dopełnienia, a `box-sizing` pozwala zarządzać układami za pomocą modelu pudełkowego CSS (CSS box model). -#### [Demo](http://codepen.io/AllThingsSmitty/pen/kkrkLL) +#### [Demonstracja](http://codepen.io/AllThingsSmitty/pen/kkrkLL) -**Uwaga:** Używanie poniższej wskazówki dotyczącej [Inherit `box-sizing`](#inherit-box-sizing) może nie uwzględniać właściwości `box-sizing` w resetowaniu CSS. +**Uwaga:** Jeżeli zdecydujesz sie na wykorzystanie powyżej opisanej wskazówki dotyczącej [Dziedziczenia `box-sizing`](#inherit-box-sizing) możesz zrezygnować z dodania `box-sizing` w zresetowanych ustawieniach CSS. [powrót do spisu treści](#powrót-do-spisu-treści ) -### Odziedzicz `box-sizing` +### Dziedziczenie `box-sizing` Niech `box-sizing` zostanie odziedziczony z `html`: @@ -71,19 +74,49 @@ html { box-sizing: border-box; } -*, *::before, *::after { +*, +*::before, +*::after { box-sizing: inherit; } ``` -Ułatwia to zmianę rozmiaru skrzynek w wtyczkach lub innych komponentach, które wykorzystują inne zachowanie. +Ułatwia to łatwiejszą zmianę `box-sizing` w wtyczkach lub innych komponentach, które wpływaja na inne zachowania. + +#### [Demonstracja](https://css-tricks.com/inheriting-box-sizing-probably-slightly-better-best-practice/) + +[powrót do spisu treści](#powrót-do-spisu-treści) + + +### Użyj `unset` zamiast resetowania wszystkich ustawień + +Podczas resetowania ustawień elementu nie jest konieczne resetowanie pojedyńczych ustawień: + +```css +button { + background: none; + border: none; + color: inherit; + font: inherit; + outline: none; + padding: 0; +} +``` + +Możesz sprecyzować wszystkie właściwości elementu, używając skrótu `all`. Używając `unset` możemy zresetować ustawienia elementu do wartości początkowych: + +```css +button { + all: unset; +} +``` [powrót do spisu treści](#powrót-do-spisu-treści) -### Use `:not()` to Apply/Unapply Borders on Navigation +### Użyj `:not()`, aby dodać/usunąć obramownie nawigacji -Zamiast zakładać granicę... +Zamiast dodać obramowanie... ```css /* add border */ @@ -92,16 +125,16 @@ Zamiast zakładać granicę... } ``` -...a następnie zdejmując go z ostatniego elementu ... +...a później usunąć ja z ostatniego elementu... ```css -/* remove border */ +/* usuń obramowanie */ .nav li:last-child { border-right: none; } ``` -...użyj `:not()` pseudo-klasy aby zastosować tylko do potrzebnych elementów: +...użyj `:not()` pseudo-klasy, aby dodać obramowanie do wybranych elementów: ```css .nav li:not(:last-child) { @@ -109,16 +142,42 @@ Zamiast zakładać granicę... } ``` -Można też użyć `.nav li + li` lub nawet `.nav li:first-child ~ li`, ale z `:not()` intencja jest bardzo jasna, a selektor CSS definiuje granicę w sposób opisany przez człowieka. +Selektor CSS definiuje granicę w sposób opisany przez człowieka. + +#### [Demonstracja](http://codepen.io/AllThingsSmitty/pen/LkymvO) + +[powrót do spisu treści](#powrót-do-spisu-treści) + + +### Sprawdź, czy czcionka jest zainstalowana lokalnie -#### [Demo](http://codepen.io/AllThingsSmitty/pen/LkymvO) +Możesz sprawdzić, czy czcionka jest zainstalowana lokalnie, przed jej zdalnym pobraniem, co również jest dobrą wskazówką dotyczącą wydajności. -[Powrót do spisu treści](#powrót-do-spisu-treści) +```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; +} +``` +Czapka dla Adama Argyle'a za podzielenie się tym prototypem i [demonstracją](https://codepen.io/argyleink/pen/VwYJpgR). -### Dodaj `wysokość linii` do `treści` +[powrót do spisu treści](#powrót-do-spisu-treści) -Nie musisz dodawać `wysokości linii` do każdego `

`, ``, _et al_. osobno. Zamiast tego dodaj go do `treści`: + +### Dodaj `line-height` do `body` + +Nie musisz dodawać `wysokości linii` do każdego `

`, ``, _et al_. osobno. Zamiast tego dodaj go do `body`: ```css body { @@ -126,12 +185,33 @@ body { } ``` -W ten sposób elementy tekstowe mogą łatwo korzystać z - `treści`. +W ten sposób elementy tekstowe mogą łatwo odziedziczyć ustawienia z `body`. + +#### [Demonstracja](http://codepen.io/AllThingsSmitty/pen/VjbdYd) + +[powrót do spisu treści](#Powrót-do-spisu-treści) + + +### Ustaw `:focus` dla elementów formularza + +Obserwowani użytkownicy klawiatury polegają na fokucie, aby określić, gdzie na stronie pojawiają się zdarzenia na klawiaturze. Skoncentruj się na elementach formy, które będą spójne, a następnie domyślna implementacja przeglądarki: + +```css +a:focus, +button:focus, +input:focus, +select:focus, +textarea:focus { + box-shadow: none; + outline: #000 dotted 2px; + outline-offset: .05em; +} +``` + +#### [Demonstracja](https://codepen.io/AllThingsSmitty/pen/ePzoOP/) -#### [Demo](http://codepen.io/AllThingsSmitty/pen/VjbdYd) +[Powrót do spisu treści](#Powrót-do-spisu-treści) -[Powrót do spisu treścis](#Powrót-do-spisu-treści) ### Przesuwanie w pionie @@ -139,7 +219,8 @@ W ten sposób elementy tekstowe mogą łatwo korzystać z Nie, to nie jest czarna magia, naprawdę możesz wyśrodkować elementy w pionie: ```css -html, body { +html, +body { height: 100%; margin: 0; } @@ -153,18 +234,27 @@ body { } ``` -Chcesz coś przeniesc? Wertykalnie, poziomo ... cokolwiek, zawsze i wszędzie CSS-Tricks ma [a nice write-up](https://css-tricks.com/centering-css-complete-guide/) dobre instrukcje na ten temat. +a także używając CSS Grid: + +```css +body { + display: grid; + height: 100vh; + margin: 0; + place-items: center center; +} +``` -**Uwaga:** Uważaj na pewne [błędne zachowanie](https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items) z Flexbox w IE11. +Chcesz coś przenieść? Pionowo, poziomo... zawsze i wszędzie? Na CSS-Tricks znajdziesz [ciekawy artykuł](https://css-tricks.com/centering-css-complete-guide/) z dobrymi instrukcje na ten temat. -#### [Demo](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) +#### [Demonstracja](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) [Powrót do spisu treści](#Powrót-do-spisu-treści) ### Listy podzielone przecinkami -Elementy listy wyglądają jak prawdziwa, oddzielona przecinkami lista: +Elementy listy mogą wyglądać jak prawdziwa, oddzielona przecinkami lista: ```css ul > li:not(:last-child)::after { @@ -172,16 +262,16 @@ ul > li:not(:last-child)::after { } ``` -Użyj `:not()` pseudo-klasy aby do ostatniego elementu nie dodano przecinka. +Użyj `:not()` pseudo-klasy, aby przecinek nie zostal dodany do ostatniego elementu. -**Uwaga:** ta wskazówka może nie być idealna dla ułatwień dostępu, w szczególności czytników ekranu.Kopiowanie / wklejanie z przeglądarki nie działa z treścią generowaną przez CSS. Postępuj ostrożnie. +**Uwaga:** Ta wskazówka może nie być idealna dla ułatwień dostępu, w szczególności na ekranach czytników. Kopiowanie / wklejanie z przeglądarki nie działa z treścią generowaną przez CSS. Postępuj ostrożnie. [Powrót do spisu treści](#Powrót-do-spisu-treści) ### Wybierz przedmioty za pomocą `nth-child` -Wybierz przedmioty za pomocą negatywnego `nth-child` w CSS, aby wybrać elementy od 1 do n. +Wybierz przedmioty nieparzyste za pomocą negatywnego `nth-child` w CSS, aby wybrać elementy od 1 do n. ```css li { @@ -194,7 +284,7 @@ li:nth-child(-n+3) { } ``` -Lub, skoro już nauczyłeś się trochę o użyciu [using `:not()`](#use-not-to-applyunapply-borders-on-navigation),wypróbuj: +Lub, skoro już nauczyłeś się trochę o użyciu [`:not()`](#use-not-to-applyunapply-borders-on-navigation),wypróbuj: ```css /* select all items except the first 3 and display them */ @@ -205,14 +295,14 @@ li:not(:nth-child(-n+3)) { To było całkiem łatwe. -#### [Demo](http://codepen.io/AllThingsSmitty/pen/WxjKZp) +#### [Demonstracja](http://codepen.io/AllThingsSmitty/pen/WxjKZp) [Powrót do spisu treści](#Powrót-do-spisu-treści) ### Użyj SVG dla ikon -Nie ma powodu, aby nie używać SVG do ikon: +Nie ma powodu, aby nie używać SVG jako ikon: ```css .logo { @@ -235,7 +325,7 @@ SVG skaluje się dobrze dla wszystkich typów rozdzielczości i jest obsługiwan ### Użyj selektora "Lobotomized Owl" -Może mieć dziwną nazwę, ale użycie uniwersalnego (`*`) z sąsiednim selektorem rodzeństwa (`+`) może zapewnić potężne możliwości CSS: +Być może "Lobotomized Owl" to dziwna nazwa dla selektora, ale użycie uniwersalnego (`*`) selektora z sąsiednim selektorem rodzeństwa (`+`) może udostepnić potężne możliwości CSS: ```css * + * { @@ -243,18 +333,18 @@ Może mieć dziwną nazwę, ale użycie uniwersalnego (`*`) z sąsiednim selekto } ``` -W tym przykładzie wszystkie elementy w przepływie dokumentu, które śledzą inne elementy, otrzymają `margin-top: 1.5em`. +W tym przykładzie wszystkie elementy, które śledzą inne elementy, otrzymają `margin-top: 1.5em`. -Aby uzyskać więcej informacji na temat selektora "lobotomized owl", przeczytaj [wpis Heydon'a Pickering](http://alistapart.com/article/axiomatic-css-and-lobotomized-owls) na *A List Apart*. +Dowiedź sie wiecej na temat selektora "lobotomized owl" czytajac [artykul Heydon'a Pickering](http://alistapart.com/article/axiomatic-css-and-lobotomized-owls) *A List Apart*. -#### [Demo](http://codepen.io/AllThingsSmitty/pen/grRvWq) +#### [Demonstracja](http://codepen.io/AllThingsSmitty/pen/grRvWq) [Powrót do spisu treści](#Powrót-do-spisu-treści) -### Użyj`max-height` dla suwaków Pure CSSs +### Użyj`max-height` (atrybutu maksymalnej wysokości) dla suwaków Pure CSS -Zaimplementuj suwaki CSS `max-height` Wysokości z ukrytym przepełnieniem: +Zaimplementuj suwaki CSS używając `max-height` z ukrytym przepełnieniem: ```css .slider { @@ -269,14 +359,14 @@ Zaimplementuj suwaki CSS `max-height` Wysokości z ukrytym przepełnieniem: } ``` -Element rozwija się do `max-height` po najechaniu kursorem, a suwak wyświetla się w wyniku przepełnienia. +Element rozwija się do `max-height` po najechaniu kursorem, a suwak wyświetla się w wyniku przepełnienia. [Powrót do spisu treści](#Powrót-do-spisu-treści) -### Równoważne komórki tabeli +### Komórki tabeli o równej-szerokości -Tabele mogą być uciążliwe, więc spróbuj `table-layout: fixed` aby utrzymać komórki na jednakowej szerokości: +Tworzenie tabel może być uciążliwe. Spróbuj użyć `table-layout: fixed`, aby upewnić sie, że komórki mają jednakową szerokość: ```css .calendar { @@ -284,16 +374,16 @@ Tabele mogą być uciążliwe, więc spróbuj `table-layout: fixed` aby utrzyma } ``` -Bezbolesne układy stołów. +Widzisz jakie to proste! :) -#### [Demo](http://codepen.io/AllThingsSmitty/pen/jALALm) +#### [Demonstracja](http://codepen.io/AllThingsSmitty/pen/jALALm) [Powrót do spisu treści](#Powrót-do-spisu-treści) ### Pozbądź się marginesów za pomocą Flexbox -Podczas pracy z rynnami kolumnowymi możesz pozbyć się `nth-`, `first-`, i `last-child` za pomocą właściwości spacji między fleksami `space-between`: +Podczas pracy z rynnami kolumnowymi (column gutters) możesz pozbyć się `nth-`, `first-`, i `last-child` za pomocą właściwości`space-between`: ```css .list { @@ -313,22 +403,22 @@ Teraz rynny kolumnowe zawsze są rozmieszczone równomiernie. ### Użyj selektorów atrybutów z pustymi linkami -Wyświetl linki, gdy element `` nie ma wartości tekstowej, ale atrybut `href` ma link: +Wyświetl linki, gdy element `` nie ma wartości tekstowej, ale atrybut `href` posiada link: ```css a[href^="http"]:empty::before { content: attr(href); } ``` -a + To całkiem wygodne. -#### [Demo](http://codepen.io/AllThingsSmitty/pen/zBzXRx) +#### [Demonstracja](http://codepen.io/AllThingsSmitty/pen/zBzXRx) [Powrót do spisu treści](#Powrót-do-spisu-treści) -### Stylizuj "Domyślne" Linki +### Stylizuj "domyślne" linki Dodaj styl dla "domyślnych" linków: @@ -339,29 +429,14 @@ a[href]:not([class]) { } ``` -Teraz linki wstawiane za pośrednictwem CMS, które zwykle nie mają atrybutu class, będą miały rozróżnienie bez generalnie wpływającego na kaskadę. - -[Powrót do spisu treści](#Powrót-do-spisu-treści) - - -### Spójny pionowy rytm - -Użyj uniwersalnego selektora (`*`) wewnątrz elementu, aby stworzyć spójny pionowy rytm: - -```css -.intro > * { - margin-bottom: 1.25rem; -} -``` - -Consistent vertical rhythm provides a visual aesthetic that makes content far more readable. +Linki wstawiane za pośrednictwem CMS, które zwykle nie mają atrybutu class, będą wyróżnione bez wpływu na kaskadę. [Powrót do spisu treści](#Powrót-do-spisu-treści) -### Indywidualne pola wyników +### Wewnętrzne proporcje bloków -Aby utworzyć pole o wewnętrznym współczynniku, wystarczy zastosować górny lub dolny margines do elementu div: +Aby utworzyć pola, które posiada wewnętrzne proporcje, wystarczy zastosować górny lub dolny margines do elementu div: ```css .container { @@ -380,21 +455,21 @@ Aby utworzyć pole o wewnętrznym współczynniku, wystarczy zastosować górny } ``` -Użycie 20% do wypełnienia sprawia, że wysokość pudełka jest równa 20% jego szerokości. Bez względu na szerokość rzutni, element div zachowa swój współczynnik proporcji (100% / 20% = 5:1). +Użycie 20% wypełnienia (padding) sprawia, że wysokość bloku jest równa 20% jego szerokości. Bez względu na szerokość okna roboczego (viewport), element div zachowa swój współczynnik proporcji (100% / 20% = 5:1). -#### [Demo](http://codepen.io/AllThingsSmitty/pen/jALZvE) +#### [Demonstracja](http://codepen.io/AllThingsSmitty/pen/jALZvE) -[Powrót do spisu treści](#Powrót-do-spisu-treści +[powrót do spisu treści](#powrót-do-spisu-treści ) -### Wystylizuj Uszkodzone Obrazy +### Wystylizuj uszkodzone obrazy -Spraw, aby uszkodzone obrazy były bardziej estetyczne z odrobiną CSS: +Spraw, aby uszkodzone obrazy były bardziej estetyczne z użyciem odrobiny CSS: ```css img { display: block; - font-family: Helvetica, Arial, sans-serif; + font-family: sans-serif; font-weight: 300; height: auto; line-height: 2; @@ -404,7 +479,7 @@ img { } ``` -Teraz dodaj reguły pseudoelementów, aby wyświetlić komunikat użytkownika i adres URL uszkodzonego obrazu: +Następnie dodaj reguły pseudoelementów, aby wyświetlić komunikat użytkownika i adres URL uszkodzonego obrazu: ```css img::before { @@ -420,13 +495,12 @@ img::after { } ``` -Dowiedz się więcej o stylizacji tego wzoru w oryginalnym poście Ire Aderinokun. [Ire Aderinokun](https://github.com/ireade/)'s [originalny post](http://bitsofco.de/styling-broken-images/). - -[Powrót do spisu treści](#Powrót-do-spisu-treści +Dowiedz się więcej o stylizacji używając tego wzoru w oryginalnym [originalny artykule](http://bitsofco.de/styling-broken-images/) [Ire Aderinokun](https://github.com/ireade/). +[powrót do spisu treści](#powrót-do-spisu-treści ) -### Użyj rem dla Global Sizing; Użyj em dla Local Sizing +### Użyj `rem` dla ustawień globalnych rozmiarow i `em` do ustawień localnych Po ustawieniu podstawowego rozmiaru czcionki w katalogu głównym (`html { font-size: 100%; }`), ustaw rozmiar czcionki dla elementów tekstowych na `em`: ```css @@ -439,7 +513,7 @@ p { } ``` -Następnie ustaw rozmiar czcionki dla modułów na `rem`: +Następnie ustaw rozmiar czcionki dla modułów na rem`: ```css article { @@ -452,15 +526,14 @@ aside .module { ``` -Teraz każdy moduł jest podzielony na sekcje i łatwiejszy do ułożenia, łatwiejszy w utrzymaniu i bardziej elastyczny. -. +Teraz każdy moduł jest podzielony na sekcje. Sprawia to żę stylizacja i utrzymanie kodu jest łątwiejsze. -[Powrót do spisu treści](#Powrót-do-spisu-treści +[powrót do spisu treści](#powrót-do-spisu-treści ) ### Ukryj filmy z autoodtwarzaniem, które nie są wyciszone -To świetna sztuczka dla niestandardowego arkusza stylów użytkownika. Unikaj przeciążania użytkownika dźwiękiem z filmu, który odtwarza się automatycznie po wczytaniu strony. Jeśli dźwięk nie jest wyciszony, nie pokazuj wideo: +To świetna sztuczka dla niestandardowego arkusza stylów użytkownika. Unikaj przeciążania użytkownika dźwiękiem z filmu, który odtwarza się automatycznie po wczytaniu strony. Jeśli dźwięk nie jest wyciszony, nie pokazuj widea: ```css video[autoplay]:not([muted]) { @@ -474,9 +547,9 @@ Po raz kolejny wykorzystujemy pseudo-klasę [`:not()`](#use-not-to-applyunapply- [Powrót do spisu treści](#Powrót-do-spisu-treści -### Użyj `:root` Tryp Elastyczny +### Użyj `:root` dla elastycznych typów -Rozmiar czcionki typowej w responsywnym układzie powinien być dostosowywany dla każdej rzutni. Możesz obliczyć rozmiar czcionki na podstawie wysokości i szerokości widoku, używając `:root`: +Rozmiar czcionki typowej w elastyczny układzie (responsive layout) powinien być dostosowywany dla każdego ekranu. Możesz obliczyć rozmiar czcionki na podstawie wysokości i szerokości okna roboczego używając `:root`: ```css :root { @@ -484,7 +557,7 @@ Rozmiar czcionki typowej w responsywnym układzie powinien być dostosowywany dl } ``` -Now you can utilize the `root em` unit based on the value calculated by `:root`: +Następnie możesz użyć jednostki`root em` na podstawie wartości obliczonej przez `:root`: ```css body { @@ -492,14 +565,14 @@ body { } ``` -#### [Demo](http://codepen.io/AllThingsSmitty/pen/XKgOkR) +#### [Demonstracja](http://codepen.io/AllThingsSmitty/pen/XKgOkR) -[Powrót do spisu treści](#Powrót-do-spisu-treści) +[powrót do spisu treści](#powrót-do-spisu-treści ) -### Ustaw `font-size` w elementach formularza, aby uzyskać lepsze wrażenia z urządzenia mobilnego +### Ustaw rozmiar czcionki w elementach formularza -Aby uniknąć korzystania z przeglądarek komurkowych (iOS Safari, _et al_.) podczas powiększania elementów formularzy HTML po dotknięciu menu rozwijanego `` dnależy dodać `font-size` do reguły selektora: ```css input[type="text"], @@ -515,8 +588,37 @@ textarea { [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, Opera, Edge, and IE11. +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 b2dcf9d8..8a1498cf 100644 --- a/translations/pt-BR/README.md +++ b/translations/pt-BR/README.md @@ -1,6 +1,6 @@ -

- light bulb icon -

+
+ light bulb icon +
# CSS Protips [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) @@ -13,16 +13,20 @@ Uma coleção de dicas para aumentar suas habilidades no 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) @@ -31,22 +35,26 @@ Uma coleção de dicas para aumentar suas habilidades no CSS. 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; @@ -55,11 +63,11 @@ Resetar o CSS vai te ajudar a manter a consistência de estilo em diferentes nav Agora os elementos estarão sem margens, preenchimento e `box-sizing`. Te permitindo gerenciar o layout com o seu CSS. -#### [Passeata](http://codepen.io/AllThingsSmitty/pen/kkrkLL) +#### [Exemplo](http://codepen.io/AllThingsSmitty/pen/kkrkLL) -**Nota:** Se você seguir a ponta [Herde o box-sizing](#herde-o-box-sizing) abaixo você pode optar por não incluir o `box-sizing` propriedade em sua redefinição de CSS. +**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) +[voltar ao índice](#Índice) ### Herde o `box-sizing` @@ -71,14 +79,44 @@ html { box-sizing: border-box; } -*, *::before, *::after { +*, +*::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](#índice) +#### [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 @@ -101,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) { @@ -109,11 +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) + + +### 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; +} +``` -#### [Passeata](http://codepen.io/AllThingsSmitty/pen/LkymvO) +Dica de chapéu para Adam Argyle por compartilhar este protip e [exemplo](https://codepen.io/argyleink/pen/VwYJpgR). -[voltar ao índice](#índice) +[voltar ao índice](#Índice) ### Defina o `line-height` no `body` @@ -128,9 +192,30 @@ body { Dessa maneira elementos de texto vão herdar o `line-height` do `body`. -#### [Passeata](http://codepen.io/AllThingsSmitty/pen/VjbdYd) +#### [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) +[voltar ao índice](#Índice) ### Alinhe Elementos Verticalmente @@ -138,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; } @@ -152,14 +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) -#### [Passeata](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) +[voltar ao índice](#Índice) -[voltar ao índice](#índice) +### 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 @@ -171,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](#índice) +[voltar ao índice](#Índice) ### Selecione Itens Usando `nth-child` Negativo @@ -193,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 -/* selecione todos os itens, exceto o primeiro 3 e exiba-os */ +/* selecione todos os itens, exceto os primeiros 3 e exiba-os */ li:not(:nth-child(-n+3)) { display: none; } @@ -204,9 +318,9 @@ li:not(:nth-child(-n+3)) { Mais fácil que isso só dois disso. -#### [Passeata](http://codepen.io/AllThingsSmitty/pen/WxjKZp) +#### [Exemplo](http://codepen.io/AllThingsSmitty/pen/WxjKZp) -[voltar ao índice](#índice) +[voltar ao índice](#Índice) ### Ícones SVG @@ -229,7 +343,7 @@ A vantagem do SVG é que o ícone fica bom em qualquer resolução, além de ter } ``` -[voltar ao índice](#índice) +[voltar ao índice](#Índice) ### Use o Seletor "Lobotomized Owl" @@ -246,9 +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*. -#### [Passeata](http://codepen.io/AllThingsSmitty/pen/grRvWq) +#### [Exemplo](http://codepen.io/AllThingsSmitty/pen/grRvWq) -[voltar ao índice](#índice) +[voltar ao índice](#Índice) ### Sliders em CSS com `max-height` @@ -270,7 +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](#índice) +[voltar ao índice](#Índice) ### Tabelas com Células de Tamanho Igual @@ -285,9 +399,9 @@ Não tem nada mais chato do que trabalhar com tabelas, mas você pode usar `tabl Tabelas sem dor de cabeça. -#### [Passeata](http://codepen.io/AllThingsSmitty/pen/jALALm) +#### [Exemplo](http://codepen.io/AllThingsSmitty/pen/jALALm) -[voltar ao índice](#índice) +[voltar ao índice](#Índice) ### Esqueça as "Margin Hacks", use Flexbox @@ -307,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](#índice) +[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 { @@ -322,40 +436,52 @@ a[href^="http"]:empty::before { Mão na roda. -#### [Passeata](http://codepen.io/AllThingsSmitty/pen/zBzXRx) +#### [Exemplo](http://codepen.io/AllThingsSmitty/pen/zBzXRx) -[voltar ao índice](#índice) +[voltar ao índice](#Índice) +### Controle Melhor a Especificidade Com `:is()` -### Estilize 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. -Defina estilos para links "default": +```css +:is(section, article, aside, nav) :is(h1, h2, h3, h4, h5, h6) { + color: green; +} +``` + +O conjunto de regras acima é equivalente às seguintes regras do seletor de números... ```css -a[href]:not([class]) { - color: #008000; - text-decoration: underline; +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; } ``` -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. +#### [Demo](https://codepen.io/AllThingsSmitty/pen/rNRVxdx) -[voltar ao índice](#índice) +> [!NOTA] +> A pseudoclasse `:is()` não é suportada em IE11. +[voltar ao índice](#Índice) -### Espaçamento Vertical Consistente +### Estilize Links "Default" -Use o seletor universal dentro de um elemento para criar um espaçamento vertical consistente: +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](#índice) +[voltar ao índice](#Índice) ### Div com Proporção de Tela Fixa @@ -381,9 +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). -#### [Passeata](http://codepen.io/AllThingsSmitty/pen/jALZvE) +#### [Exemplo](http://codepen.io/AllThingsSmitty/pen/jALZvE) -[voltar ao índice](#índice) +[voltar ao índice](#Índice) ### Estilize Imagens Quebradas @@ -393,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; @@ -403,7 +529,7 @@ 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 { @@ -421,7 +547,7 @@ 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](#índice) +[voltar ao índice](#Índice) ### Use `rem` para Definir Tamanhos Globais; Use `em` para Definir Tamanhos Locais @@ -452,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](#índice) +[voltar ao índice](#Índice) ### Esconda Vídeos em Autoplay Que Não Estejam no Mudo @@ -465,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](#índice) +[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 { @@ -488,12 +614,11 @@ body { } ``` -#### [Passeata](http://codepen.io/AllThingsSmitty/pen/XKgOkR) +#### [Exemplo](http://codepen.io/AllThingsSmitty/pen/XKgOkR) -[voltar ao índice](#índice) +[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 6b4ef6c8..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) @@ -22,9 +22,13 @@ 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. [Выровнять все по вертикали](#Выровнять-все-по-вертикали) +1. [Установите `:focus` для элементов формы](#Установите-focus-для-элементов-формы) +1. [Выровнять всё по вертикали](#Выровнять-всё-по-вертикали) +1. [Используйте `aspect-ratio` вместо задания ширины, высоты](#Используйте-aspect-ratio-вместо-задания-ширины-высоты) 1. [Списки, разделенные запятыми](#Списки-разделенные-запятыми) 1. [Выбирайте элементы с использованием отрицательных значений в `nth-child`](#Выбирайте-элементы-с-использованием-отрицательных-значений-в-nth-child) 1. [Используйте SVG для значков](#Используйте-svg-для-значков) @@ -33,14 +37,17 @@ 1. [Ячейки таблицы равной ширины](#Ячейки-таблицы-равной-ширины) 1. [Используйте Flexbox вместо margin](#Используйте-flexbox-вместо-margin) 1. [Используйте селектор атрибутов для пустых ссылок](#Используйте-селектор-атрибутов-для-пустых-ссылок) +1. [Управляйте специфичностью лучше, с помощью `:is()`](#Управляйте-специфичностью-лучше-с-помощью-is) 1. [Стиль "по умолчанию" для ссылок](#тиль-по-умолчанию-для-ссылокs) -1. [Постоянный вертикальный ритм](#Постоянный-вертикальный-ритм) 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 @@ -48,7 +55,9 @@ Сброс CSS помогает обеспечить согласованность стилей между различными браузерами и с чистого листа начать оформление элементов. Вы можете использовать CSS библиотеки сброса такие как [Normalize](http://necolas.github.io/normalize.css/) и др., или вы можете использовать более простой способ сброса: ```css -* { +*, +*::before, +*::after { box-sizing: border-box; margin: 0; padding: 0; @@ -59,7 +68,7 @@ #### [Демо](http://codepen.io/AllThingsSmitty/pen/kkrkLL) -**Примечание:** Если вы будете следовать совету [Наследуйте box-sizing](#inherit-box-sizing), то вы можете не включать свойство `box-sizing` в ваш CSS Reset. +**Примечание:** Если вы будете следовать совету [Наследуйте `box-sizing`](#inherit-box-sizing), то вы можете не включать свойство `box-sizing` в ваш CSS Reset. [вернуться к оглавлению](#table-of-contents) @@ -73,13 +82,43 @@ html { box-sizing: border-box; } -*, *::before, *::after { +*, +*::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) @@ -111,13 +150,39 @@ html { } ``` -Конечно, вы можете использовать `.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`: @@ -135,12 +200,32 @@ body { [вернуться к оглавлению](#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; +} +``` + +[вернуться к оглавлению](#table-of-contents) + + +### Выровнять всё по вертикали -Нет, это не черная магия, вы действительно можете расположить элементы по центру по вертикали: +Нет, это не чёрная магия, вы действительно можете расположить элементы по центру по вертикали: ```css -html, body { +html, +body { height: 100%; margin: 0; } @@ -154,15 +239,42 @@ body { } ``` -Хотите разместить по центру что-то еще? Вертикально, горизонтально...что угодно, в любое время и в любом месте? У нас есть [хорошая статья](https://css-tricks.com/centering-css-complete-guide/) которая научит всему этому. +...а также с помощью CSS Grid: -**Примечание:** Будьте осторожны с некоторыми [багами](https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items) flexbox в IE11. +```css +body { + display: grid; + height: 100vh; + margin: 0; + place-items: center center; +} +``` + +Хотите разместить по центру что-то еще? Вертикально, горизонтально...что угодно, в любое время и в любом месте? У нас есть [хорошая статья](https://css-tricks.com/centering-css-complete-guide/) которая научит всему этому. #### [Демо](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) + + ### Списки, разделенные запятыми Сделайте список похожим на настоящий, разделенный запятыми список: @@ -329,33 +441,44 @@ a[href^="http"]:empty::before { [вернуться к оглавлению](#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) @@ -395,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; @@ -513,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`: +当触发`` 的下拉選單時在 HTML 表單元素進行縮放,你可以加上`font-size` 到這些選取器樣式規則: + +```css +input[type='text'], +input[type='number'], +select, +textarea { + font-size: 16px; +} +``` + +: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; +} +``` + +[回目錄](#目錄) + + +## 瀏覽器支援度 + +以上技巧支援 Chrome, Firefox, Safari, 最新版本與 Edge 瀏覽器。