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 c3498a63..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-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 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/knowledge/blob/master/github/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 2fc40830..514038b3 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,20 @@ -

+

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 @@ -23,10 +22,11 @@ A collection of tips to help take your CSS skills pro. 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. [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) @@ -35,6 +35,7 @@ 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. [Intrinsic Ratio Boxes](#intrinsic-ratio-boxes) 1. [Style Broken Images](#style-broken-images) @@ -45,11 +46,11 @@ A collection of tips to help take your CSS skills pro. 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 *, @@ -63,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` @@ -90,8 +91,7 @@ This makes it easier to change `box-sizing` in plugins or other components that #### [Demo](https://css-tricks.com/inheriting-box-sizing-probably-slightly-better-best-practice/) -[back to table of contents](#table-of-contents) - +[Back to top](#contents) ### Use `unset` Instead of Resetting All Properties @@ -116,10 +116,7 @@ button { } ``` -**Note:** the `all` and `unset` shorthand isn't supported in IE11. - -[back to table of contents](#table-of-contents) - +[Back to top](#contents) ### Use `:not()` to Apply/Unapply Borders on Navigation @@ -151,12 +148,11 @@ Instead of putting on the border... Here, the CSS selector is read as a human would describe it. -#### [Demo](http://codepen.io/AllThingsSmitty/pen/LkymvO) - -[back to table of contents](#table-of-contents) +#### [Demo](https://codepen.io/AllThingsSmitty/pen/LkymvO) +[Back to top](#contents) -### Check If Font Is Installed Locally +### 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. @@ -164,12 +160,8 @@ You can check if a font is installed locally before fetching it remotely, which @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"); + /* Full name */ local("Dank Mono"), /* Postscript name */ local("Dank Mono"), + /* Otherwise, download it! */ url("//...a.server/fonts/DankMono.woff"); } code { @@ -179,8 +171,7 @@ code { H/T to Adam Argyle for sharing this protip and [demo](https://codepen.io/argyleink/pen/VwYJpgR). -[back to table of contents](#table-of-contents) - +[Back to top](#contents) ### Add `line-height` to `body` @@ -194,10 +185,9 @@ body { This way textual elements can inherit from `body` easily. -#### [Demo](http://codepen.io/AllThingsSmitty/pen/VjbdYd) - -[back to table of contents](#table-of-contents) +#### [Demo](https://codepen.io/AllThingsSmitty/pen/VjbdYd) +[Back to top](#contents) ### Set `:focus` for Form Elements @@ -211,14 +201,13 @@ select:focus, textarea:focus { box-shadow: none; outline: #000 dotted 2px; - outline-offset: .05em; + outline-offset: 0.05em; } ``` #### [Demo](https://codepen.io/AllThingsSmitty/pen/ePzoOP/) -[back to table of contents](#table-of-contents) - +[Back to top](#contents) ### Vertically-Center Anything @@ -228,15 +217,12 @@ No, it's not black magic, you really can center elements vertically. You can do 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; } ``` @@ -246,20 +232,33 @@ body { body { display: grid; height: 100vh; - margin: 0; - place-items: center center; + 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. -Want to center something else? Vertically, horizontally...anything, anytime, anywhere? CSS-Tricks has [a nice write-up](https://css-tricks.com/centering-css-complete-guide/) on doing all of that. +#### [Demo](https://codepen.io/AllThingsSmitty/pen/GqmGqZ) -**Note:** Watch for some [buggy behavior](https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items) with flexbox in IE11. +[Back to top](#contents) -#### [Demo](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) +### Use `aspect-ratio` Instead of Height/Width -[back to table of contents](#table-of-contents) +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 @@ -273,10 +272,10 @@ ul > li:not(:last-child)::after { Use the `:not()` pseudo-class and no comma will be added to the last item. -**Note:** This tip may not be ideal for accessibility, specifically screen readers. And copy/paste from the browser doesn't work with CSS-generated content. Proceed with caution. - -[back to table of contents](#table-of-contents) +> [!NOTE] +> This tip may not be ideal for accessibility, specifically screen readers. And copy/paste from the browser doesn't work with CSS-generated content. Proceed with caution. +[Back to top](#contents) ### Select Items Using Negative `nth-child` @@ -288,7 +287,7 @@ li { } /* select items 1 through 3 and display them */ -li:nth-child(-n+3) { +li:nth-child(-n + 3) { display: block; } ``` @@ -297,15 +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)) { +li:not(:nth-child(-n + 3)) { display: block; } ``` -#### [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 @@ -319,7 +317,8 @@ 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). 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 { @@ -327,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 @@ -342,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*. - -#### [Demo](http://codepen.io/AllThingsSmitty/pen/grRvWq) +> [!TIP] +> For more on the "lobotomized owl" selector, read [Heydon Pickering's post](http://alistapart.com/article/axiomatic-css-and-lobotomized-owls) on _A List Apart_. -[back to table of contents](#table-of-contents) +#### [Demo](https://codepen.io/AllThingsSmitty/pen/grRvWq) +[Back to top](#contents) ### Use `max-height` for Pure CSS Sliders @@ -368,8 +366,7 @@ 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 @@ -383,10 +380,9 @@ Tables can be a pain to work with. Try using `table-layout: fixed` to keep cells 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 @@ -405,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 @@ -418,14 +413,59 @@ a[href^="http"]:empty::before { } ``` -That's pretty convenient. +That's really convenient. + +#### [Demo](https://codepen.io/AllThingsSmitty/pen/zBzXRx) + +> [!NOTE] +> This tip may not be ideal for accessibility, specifically screen readers. And copy/paste from the browser doesn't work with CSS-generated content. Proceed with caution. + +[Back to top](#contents) + +### Control Specificity Better with `:is()` -**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. +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. -#### [Demo](http://codepen.io/AllThingsSmitty/pen/zBzXRx) +```css +:is(section, article, aside, nav) :is(h1, h2, h3, h4, h5, h6) { + color: green; +} +``` + +The above ruleset is equivalent to the following number selector rules... + +```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; +} +``` -[back to table of contents](#table-of-contents) +#### [Demo](https://codepen.io/AllThingsSmitty/pen/rNRVxdx) +[Back to top](#contents) ### Style "Default" Links @@ -440,8 +480,7 @@ a[href]:not([class]) { Now links that are inserted via a CMS, which don't usually have a `class` attribute, will have a distinction without generically affecting the cascade. -[back to table of contents](#table-of-contents) - +[Back to top](#contents) ### Intrinsic Ratio Boxes @@ -466,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 @@ -504,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 @@ -531,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 @@ -552,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 @@ -561,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); } ``` @@ -573,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 @@ -591,10 +626,7 @@ textarea { } ``` -:dancer: - -[back to table of contents](#table-of-contents) - +[Back to top](#contents) ### Use Pointer Events to Control Mouse Events @@ -602,15 +634,14 @@ textarea { ```css button:disabled { - opacity: .5; + opacity: 0.5; pointer-events: none; } ``` It's that simple. -[back to table of contents](#table-of-contents) - +[Back to top](#contents) ### Set `display: none` on Line Breaks Used as Spacing @@ -622,12 +653,11 @@ br + br { } ``` -[back to table of contents](#table-of-contents) - +[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. +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 { @@ -635,36 +665,58 @@ If you have HTML elements that are empty, i.e., the content has yet to be set ei } ``` -**Note:** Keep in mind that elements with whitespace aren't considered empty, e.g., `

`. - -[back to table of contents](#table-of-contents) +> [!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 -**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 may 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 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/translations/de-DE/README.md b/translations/de-DE/README.md index aa6b92a4..821701a2 100644 --- a/translations/de-DE/README.md +++ b/translations/de-DE/README.md @@ -114,8 +114,6 @@ button { } ``` -**Hinweis:** Die Kurzform `all` und "unset" wird in IE11 nicht unterstützt. - [zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) @@ -254,8 +252,6 @@ body { Möchtest du etwas anderes zentrieren? Vertikal, horizontal… alles, jederzeit, überall? CSS-Tricks hat [eine schöne Ausarbeitung](https://css-tricks.com/centering-css-complete-guide/) über all dies. -**Hinweis:** Passe auf das [fehlerhafte Verhalten](https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items) von Flexbox in IE11 auf. - #### [Demo](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) [zurück zum Inhaltsverzeichnis](#inhaltsverzeichnis) @@ -625,4 +621,4 @@ br + br { ## Unterstützung -Aktuelle Versionen von Chrome, Firefox, Safari, Opera, Edge und IE11. \ No newline at end of file +Aktuelle Versionen von Chrome, Firefox, Safari, und Edge. \ No newline at end of file diff --git a/translations/es-ES/README.md b/translations/es-ES/README.md index 77e2a9dc..20c373d6 100644 --- a/translations/es-ES/README.md +++ b/translations/es-ES/README.md @@ -115,8 +115,6 @@ button { } ``` -**Nota:** la abreviatura `all` y` unset` no es compatible con IE11. - [volver al índice de contenidos](#tabla-de-contenido) @@ -253,8 +251,6 @@ body { ¿Quieres centrar algo más? Vertical, horizontal… cualquier cosa, en cualquier momento y en cualquier lugar? CSS-Tricks tiene [un bonito artículo](https://css-tricks.com/centering-css-complete-guide/) para hacer todo eso. -**Nota:** mira algunos [comportamientos erróneos](https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items) de Flexbox en IE11. - #### [Demo](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) [volver al índice de contenidos](#tabla-de-contenido) @@ -639,4 +635,4 @@ br + br { ## Soporte -Las versiones actuales de Chrome, Firefox, Safari, Opera, Edge y IE11. +Las versiones actuales de Chrome, Firefox, Safari y Edge. diff --git a/translations/fr-FR/README.md b/translations/fr-FR/README.md index de8424fc..c445c8c0 100644 --- a/translations/fr-FR/README.md +++ b/translations/fr-FR/README.md @@ -115,8 +115,6 @@ button { } ``` -**Remarque:** les raccourcis `all` et` unset` ne sont pas pris en charge dans IE11. - [retour à la table des matières](#table-des-matières) @@ -252,8 +250,6 @@ body { Vous voulez centrer autre chose ? Verticalement, horizontalement... quoi que ce soit, à tout moment, en tout lieu ? CSS-Tricks a [un article sympa](https://css-tricks.com/centering-css-complete-guide/) sur comment faire tout cela. -**Remarque:** Surveillez certains [comportement bogués](https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items) avec flexBox dans IE11. - #### [Démo](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) [retour à la table des matières](#table-des-matières) @@ -625,4 +621,4 @@ br + br { ## Prise en charge par les navigateurs -Les versions actuelles de Chrome, Firefox, Safari, Opera, Edge, et IE11. +Les versions actuelles de Chrome, Firefox, Safari, et Edge. diff --git a/translations/gr-GR/README.md b/translations/gr-GR/README.md index e3078d52..1f1ad625 100644 --- a/translations/gr-GR/README.md +++ b/translations/gr-GR/README.md @@ -114,8 +114,6 @@ button { } ``` -**Σημείωση:** η στενογραφία «all` και` unset` δεν υποστηρίζεται στο IE11. - [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) @@ -254,8 +252,6 @@ body { Θέλετε να κεντραρίσετε κάτι άλλο? Vertically, Κάθετα, οριζόντια...όπως θέλετε,όποτε θέλετε, παντού? Το CSS-Tricks έχει [a nice write-up](https://css-tricks.com/centering-css-complete-guide/) on doing all of that. -**Σημείωση:** Προσοχή για ενδεχόμενη [buggy συμπεριφορά](https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items) with flexbox in IE11. - #### [Demo](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) @@ -624,6 +620,6 @@ br + br { ## Υποστήριξη -Οι τωρινές εκδόσεις των Chrome, Firefox, Safari, Opera, Edge, καθώς και IE11. +Οι τωρινές εκδόσεις των Chrome, Firefox, Safari, καθώς και Edge. [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) diff --git a/translations/gu-IND/README.md b/translations/gu-IND/README.md index 73278557..f1d37d96 100644 --- a/translations/gu-IND/README.md +++ b/translations/gu-IND/README.md @@ -250,8 +250,6 @@ body { કેન્દ્ર માંગો છો કંઈક બીજું? વર્ટિકલ, આડા...કંઈપણ, કોઈપણ સમયે, ગમે ત્યાં? CSS-Tricks has [a nice write-up](https://css-tricks.com/centering-css-complete-guide/) on કરવાનું બધા કે. -**નોટ:** જુઓ કેટલાક માટે [buggy behavior](https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items) સાથે flexbox માં IE11. - #### [પ્રદર્શન](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) [સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) @@ -623,6 +621,6 @@ br + br { ## આધાર -વર્તમાન આવૃત્તિઓ 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 7b03e423..49ef54e5 100644 --- a/translations/it-IT/README.md +++ b/translations/it-IT/README.md @@ -114,8 +114,6 @@ button { } ``` -**Nota:** la stenografia `all` e` unset` non è supportata in IE11. - [torna al sommario](#sommario) @@ -252,8 +250,6 @@ 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. -**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. - #### [Dimostrazione](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) [torna al sommario](#sommario) @@ -625,4 +621,4 @@ br + br { ## Supporto -Le attuali versioni di Chrome, Firefox, Safari, Opera, Edge ed IE11. \ No newline at end of file +Le attuali versioni di Chrome, Firefox, Safari, ed Edge. \ No newline at end of file diff --git a/translations/ja-JP/README.md b/translations/ja-JP/README.md index ab0d45aa..2ad307d9 100644 --- a/translations/ja-JP/README.md +++ b/translations/ja-JP/README.md @@ -127,8 +127,6 @@ button { } ``` -**備考:** IE11では `all`および` unset`の省略形はサポートされていません。 - [目次へ戻る](#table-of-contents) @@ -272,8 +270,6 @@ body { なんでも中央に揃いたいですか? CSS-Tricks の[セントリングガイド](https://css-tricks.com/centering-css-complete-guide/) をチェックしてください。 -**備考:** IE11のFlexboxの [バグを気をつけてください](https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items) - #### [デモ](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) [目次へ戻る](#table-of-contents) @@ -682,4 +678,4 @@ br + br { ## サポート -現在のChrome, Firefox, Safari, Opera と EdgeのバージョンとIE11. +現在のChrome, Firefox, Safari, のバージョンとEdge. diff --git a/translations/ko-KR/readme.md b/translations/ko-KR/readme.md index f1fdeb0e..2cd47c2d 100644 --- a/translations/ko-KR/readme.md +++ b/translations/ko-KR/readme.md @@ -125,8 +125,6 @@ button { } ``` -**Note:** `all` 및`unset` 속기는 IE11에서 지원되지 않습니다. - [목차로 돌아가기](#table-of-contents) @@ -259,11 +257,8 @@ body { } ``` - 무언가를 중앙으로 배치하고 싶으신가요? 가로로, 세로로 ...뭐든지, 어떤 때라도, 어디서든? CSS-Tricks의 [가이드](https://css-tricks.com/centering-css-complete-guide/)를 통해 그 모든 것을 해보세요! -**Note:** IE11의 Flexbox의 [버그를 주의해 주세요](https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items) - #### [데모](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) [목차로 돌아가기](#table-of-contents) @@ -670,7 +665,7 @@ br + br { ## 지원 -최신 버전의 Chrome, Firefox, Safari, Opera, Edge, IE11에서 지원됩니다.. +최신 버전의 Chrome, Firefox, Safari, Edge에서 지원됩니다.. [목차로 돌아가기](#table-of-contents) diff --git a/translations/pl-PL/README.md b/translations/pl-PL/README.md index f9f09ec2..c2e9788d 100644 --- a/translations/pl-PL/README.md +++ b/translations/pl-PL/README.md @@ -111,8 +111,6 @@ button { } ``` -**Uwaga:** skróty `all` i `unset` nie są obsługiwane w IE11. - [powrót do spisu treści](#powrót-do-spisu-treści) @@ -249,8 +247,6 @@ body { 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. -**Uwaga:** Uważaj na pewne [nieprawidłowe zachowanie](https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items) z Flexbox w IE11. - #### [Demonstracja](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) [Powrót do spisu treści](#Powrót-do-spisu-treści) @@ -623,6 +619,6 @@ br + br { ## 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 e8fb02db..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,7 +13,7 @@ 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 @@ -26,6 +26,7 @@ Uma coleção de dicas para aumentar suas habilidades no CSS. 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) @@ -34,6 +35,7 @@ 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. [Div com Proporção de Tela Fixa](#div-com-proporção-de-tela-fixa) 1. [Estilize Imagens Quebradas](#estilize-imagens-quebradas) @@ -43,6 +45,7 @@ Uma coleção de dicas para aumentar suas habilidades no CSS. 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 @@ -113,8 +116,6 @@ button { } ``` -**Nota:** a abreviação `all` e` unset` não é compatível com o IE11. - [voltar ao índice](#Índice) @@ -250,12 +251,29 @@ body { Isso não resolveu seu problema? O site CSS-Tricks tem [um guia completo](https://css-tricks.com/centering-css-complete-guide/) de como centralizar elementos com CSS. -**Aviso:** Fique atento com os [bugs](https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items) quando utilizar flexbox no IE11. - #### [Exemplo](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) [voltar ao índice](#Índice) +### 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 @@ -422,6 +440,33 @@ Mão na roda. [voltar ao índice](#Índice) +### Controle Melhor a Especificidade Com `:is()` + +A pseudoclasse `:is()` é usada para marca vários seletores de uma só vez, reduzindo a redundância e melhorando a legibilidade do código. Isso é extremamente útil para escrever seletores grandes de uma forma mais compacta. + +```css +: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 +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) + +> [!NOTA] +> A pseudoclasse `:is()` não é suportada em IE11. + +[voltar ao índice](#Índice) ### Estilize Links "Default" @@ -619,7 +664,23 @@ br + br { [voltar ao índice](#Índice) +### Use `:empty` para Esconder Elementos HTML Vazios + +Se você tem elementos HTML vazios, ou seja, o conteúdo ainda tem que ser definido ou pela CMS ou injetado dinamicamente (e.g., `

`) e está criando espaços indesejáveis no seu layout, use a pseudoclasse `:empty` para esconder os elementos no layout. + +```css +:empty { + display: none; +} +``` + +> [!NOTA] +> Lembre-se que os elementos com espaços em branco não são considerados vazios, e.g., `

`. + +[voltar ao índice](#Índice) ## Suporte -Versões atuais do Chrome, Firefox, Safari, Opera, Edge, e IE11. +Versões atuais do Chrome, Firefox, Safari, e Edge. + +[voltar ao índice](#Índice) \ No newline at end of file diff --git a/translations/pt-PT/README.md b/translations/pt-PT/README.md index 550ab4b4..f8af537e 100644 --- a/translations/pt-PT/README.md +++ b/translations/pt-PT/README.md @@ -114,8 +114,6 @@ button { } ``` -**Nota:** a abreviação `all` e` unset` não é compatível com o IE11. - [voltar ao índice](#Índice) @@ -251,8 +249,6 @@ body { Isto não resolveu o teu problema? O site CSS-Tricks tem [um guia completo](https://css-tricks.com/centering-css-complete-guide/) em como centralizar elementos com CSS. - **Aviso:** Fica atento aos [bugs](https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items) quando estás a utilizar a flexbox no IE11. - #### [Passeata](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) [Regressar ao índice](#Índice) @@ -624,4 +620,4 @@ br + br { ## Suporte -Versões atuais do Chrome, Firefox, Safari, Opera, Edge, e IE11. +Versões atuais do Chrome, Firefox, Safari, e Edge. diff --git a/translations/ru-RU/README.md b/translations/ru-RU/README.md index f44223a0..db8c5338 100644 --- a/translations/ru-RU/README.md +++ b/translations/ru-RU/README.md @@ -24,10 +24,11 @@ 1. [Наследуйте `box-sizing`](#Наследуйте-box-sizing) 1. [Используйте `unset` вместо сброса всех свойств](#Используйте-unset-вместо-сброса-всех-свойств) 1. [Используйте `:not()` для добавления / удаления границ в меню навигации](#Используйте-not-для-добавления--удаления-границ-в-меню-навигации) -1. [проверьте, установлен ли шрифт локально](#проверьте,-установлен-ли-шрифт-локально) +1. [Проверьте, установлен ли шрифт локально](#проверьте,-установлен-ли-шрифт-локально) 1. [Добавьте `line-height` в `body`](#Добавьте-line-height-в-body) 1. [Установите `:focus` для элементов формы](#Установите-focus-для-элементов-формы) -1. [Выровнять все по вертикали](#Выровнять-все-по-вертикали) +1. [Выровнять всё по вертикали](#Выровнять-всё-по-вертикали) +1. [Используйте `aspect-ratio` вместо задания ширины, высоты](#Используйте-aspect-ratio-вместо-задания-ширины-высоты) 1. [Списки, разделенные запятыми](#Списки-разделенные-запятыми) 1. [Выбирайте элементы с использованием отрицательных значений в `nth-child`](#Выбирайте-элементы-с-использованием-отрицательных-значений-в-nth-child) 1. [Используйте SVG для значков](#Используйте-svg-для-значков) @@ -36,6 +37,7 @@ 1. [Ячейки таблицы равной ширины](#Ячейки-таблицы-равной-ширины) 1. [Используйте Flexbox вместо margin](#Используйте-flexbox-вместо-margin) 1. [Используйте селектор атрибутов для пустых ссылок](#Используйте-селектор-атрибутов-для-пустых-ссылок) +1. [Управляйте специфичностью лучше, с помощью `:is()`](#Управляйте-специфичностью-лучше-с-помощью-is) 1. [Стиль "по умолчанию" для ссылок](#тиль-по-умолчанию-для-ссылокs) 1. [Блок с собственным отношением сторон](#Блок-с-собственным-отношением-сторон) 1. [Задайте стили для поломанныx изображений](#Задайте-стили-для-поломанныx-изображений) @@ -45,6 +47,7 @@ 1. [Установите `font-size` для элементов формы, чтобы оптимизировать просмотр на мобильных устройствах](#Установите-font-size-для-элементов-формы-чтобы-оптимизировать-просмотр-на-мобильных-устройствах) 1. [Использовать события указателя для управления событиями мыши](#Использовать-события-указателя-для-управления-событиями-мыши) 1. [Установите `display: none` на разрывы строк, используемые как интервалы](#Установите-display-none-на-разрывы-строк-используемые-как-интервалы) +1. [Используйте `:empty`, чтобы скрыть пустые HTML элементы](#Используйте-empty-чтобы-скрыть-пустые-HTML-элементы) ### Используйте CSS Reset @@ -65,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) @@ -116,8 +119,6 @@ button { } ``` -**Примечание:** сокращенные обозначения `all` и `unset` не поддерживаются в IE11. - [вернуться к оглавлению](#table-of-contents) @@ -156,7 +157,7 @@ button { [вернуться к оглавлению](#table-of-contents) -### проверьте, установлен ли шрифт локально +### Проверьте, установлен ли шрифт локально Вы можете проверить, установлен ли шрифт локально, прежде чем извлекать его удаленно, что также является хорошим показателем производительности. @@ -218,9 +219,9 @@ textarea:focus { [вернуться к оглавлению](#table-of-contents) -### Выровнять все по вертикали +### Выровнять всё по вертикали -Нет, это не черная магия, вы действительно можете расположить элементы по центру по вертикали: +Нет, это не чёрная магия, вы действительно можете расположить элементы по центру по вертикали: ```css html, @@ -251,13 +252,29 @@ body { Хотите разместить по центру что-то еще? Вертикально, горизонтально...что угодно, в любое время и в любом месте? У нас есть [хорошая статья](https://css-tricks.com/centering-css-complete-guide/) которая научит всему этому. -**Примечание:** Будьте осторожны с некоторыми [багами](https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items) flexbox в IE11. - #### [Демо](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) [вернуться к оглавлению](#table-of-contents) +### Используйте `aspect-ratio` вместо задания ширины, высотыhttps://onelove-agency.ru/web/october2024 + +Свойство `aspect-ratio` позволяет легко изменять размеры элементов и поддерживать постоянное соотношение ширины и высоты. Это невероятно полезно в отзывчивом веб-дизайне для предотвращения смещения макета. Используйте `object-fit` вместе с ним, чтобы не нарушить верстку при изменении значений высоты/ширины изображений. + +```css +img { + aspect-ratio: 16 / 9; /* ширина / высота */ + object-fit: cover; +} +``` + +Подробнее о свойстве ` aspect-ratio` читайте в этой статье [web.dev post](https://web.dev/articles/aspect-ratio). + +#### [Демо](https://codepen.io/AllThingsSmitty/pen/MWxwoNx/) + +[вернуться к оглавлению](#table-of-contents) + + ### Списки, разделенные запятыми Сделайте список похожим на настоящий, разделенный запятыми список: @@ -424,6 +441,32 @@ a[href^="http"]:empty::before { [вернуться к оглавлению](#table-of-contents) +### Управляйте специфичностью лучше, с помощью `:is() + +Псевдокласс `:is()` используется для одновременного обращения к нескольким селекторам, что уменьшает избыточность и улучшает читаемость кода. Это невероятно полезно для написания больших селекторов в более компактной форме. + +```css +:is(section, article, aside, nav) :is(h1, h2, h3, h4, h5, h6) { + color: green; +} +``` + +Приведённый выше набор правил эквивалентен следующим правилам селектора чисел... + +```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) + + ### Стиль "по умолчанию" для ссылок Добавьте для ссылок стиль "по умолчанию": @@ -595,7 +638,7 @@ textarea { ### Использовать события указателя для управления событиями мыши -[События указателя] (https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events) позволяют указать, как мышь взаимодействует с элементом, который он трогает. Чтобы отключить событие указателя по умолчанию на кнопке, например: +[События указателя](https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events) позволяют указать, как мышь взаимодействует с элементом, который он трогает. Чтобы отключить событие указателя по умолчанию на кнопке, например: ```css button:disabled { @@ -611,7 +654,7 @@ button:disabled { ### Установите `display: none` на разрывы строк, используемые как интервалы -Как отметил [Гарри Робертс] (https://twitter.com/csswizardry/status/1170835532584235008), это может помочь пользователям CMS использовать дополнительные разрывы строк для пробелов: +Как отметил [Гарри Робертс](https://twitter.com/csswizardry/status/1170835532584235008), это может помочь пользователям CMS использовать дополнительные разрывы строк для пробелов: ```css br + br { @@ -622,6 +665,23 @@ br + br { [вернуться к оглавлению](#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 index fcddc58c..04271192 100644 --- a/translations/vn-VN/README.md +++ b/translations/vn-VN/README.md @@ -115,8 +115,6 @@ button { } ``` -**Note:** tốc độ viết tắt `all` và` unset` không được hỗ trợ trong IE11. - [back to table of contents](#table-of-contents) @@ -253,8 +251,6 @@ body { 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 đó. -**Note:** Xem một ít [buggy behavior](https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items) với Flexbox trên IE11. - #### [Demo](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) [back to table of contents](#table-of-contents) @@ -624,4 +620,4 @@ br + br { ## Support - versions hiện tại Chrome, Firefox, Safari, Opera, Edge, and IE11. + versions hiện tại Chrome, Firefox, Safari, và Edge. diff --git a/translations/zh-CN/README.md b/translations/zh-CN/README.md index 619d4b00..e9be9286 100644 --- a/translations/zh-CN/README.md +++ b/translations/zh-CN/README.md @@ -117,8 +117,6 @@ button { } ``` -**注意:** IE11不支持`all`和`unset`的简写。 - [回目录](#目录) @@ -254,8 +252,6 @@ body { 这还不够?垂直方向,水平方向?任何元素,任何时间,任何地点?CSS-Tricks [有篇好文](https://css-tricks.com/centering-css-complete-guide/) 讲到了各种居中的技巧。 -**注意:** IE11 对 flexbox 的支持[有点 bug](https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items)。 - #### [演示](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) [回目录](#目录) @@ -642,4 +638,4 @@ br + br { ### 支持情况 -这些技巧适用于最新版的 Chrome, Firefox, Safari, Opera, Edge, 以及 IE11。 +这些技巧适用于最新版的 Chrome, Firefox, Safari, 以及 Edge。 diff --git a/translations/zh-TW/README.md b/translations/zh-TW/README.md index 7e07c033..e52217b5 100644 --- a/translations/zh-TW/README.md +++ b/translations/zh-TW/README.md @@ -115,8 +115,6 @@ button { } ``` -**注意:** IE11不支持`all`和`unset`的简写。 - [回到目錄](#table-of-contents) ### 使用 `:not()` 選擇器來決定表單是否顯示邊框 @@ -251,8 +249,6 @@ body { 還想居中排版其他的東西?垂直居中、水平居中、... 任何事、任何時間、任何地點?CSS-Tricks [有篇不錯的文章](https://css-tricks.com/centering-css-complete-guide/) 提到了各種居中排版的技巧。 -**注意:** IE11 的 flexbox [有些怪怪的行為](https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items) 要注意。 - #### [示範](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) [回到目錄](#table-of-contents) @@ -609,4 +605,4 @@ br + br { ## 瀏覽器支援度 -以上技巧支援 Chrome, Firefox, Safari, Opera, Edge 最新版本與 IE11 瀏覽器。 +以上技巧支援 Chrome, Firefox, Safari, 最新版本與 Edge 瀏覽器。