Repository: AllThingsSmitty/css-protips Branch: master Commit: e95123993037 Files: 19 Total size: 261.9 KB Directory structure: gitextract_nmqogxqr/ ├── CODE-OF-CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md └── translations/ ├── de-DE/ │ └── README.md ├── es-ES/ │ └── README.md ├── fr-FR/ │ └── README.md ├── gr-GR/ │ └── README.md ├── gu-IND/ │ └── README.md ├── it-IT/ │ └── README.md ├── ja-JP/ │ └── README.md ├── ko-KR/ │ └── readme.md ├── pl-PL/ │ └── README.md ├── pt-BR/ │ └── README.md ├── pt-PT/ │ └── README.md ├── ru-RU/ │ └── README.md ├── vn-VN/ │ └── README.md ├── zh-CN/ │ └── README.md └── zh-TW/ └── README.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: CODE-OF-CONDUCT.md ================================================ # Contributor Code of Conduct As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery * Personal attacks * Trolling or insulting/derogatory comments * Public or private harassment * Publishing other's private information, such as physical or electronic addresses, without explicit permission * Other unethical or unprofessional conduct Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. 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 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/). ================================================ FILE: CONTRIBUTING.md ================================================ # Contribution Guidelines 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. ## 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 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! ## 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 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. ================================================ FILE: LICENSE ================================================ CC0 1.0 Universal Statement of Purpose The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work"). Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others. For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights. 1. Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following: i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work; ii. moral rights retained by the original author(s) and/or performer(s); iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work; iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below; v. rights protecting the extraction, dissemination, use and reuse of data in a Work; vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof. 2. Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose. 3. Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose. 4. Limitations and Disclaimers. a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document. b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law. c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work. d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. For more information, please see ================================================ FILE: README.md ================================================
light bulb icon
# 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 - [Protips](#protips) - [Support](#support) - [Translations](#translations) - [Contribution Guidelines](CONTRIBUTING.md) ## Protips 1. [Use a CSS Reset](#use-a-css-reset) 1. [Inherit `box-sizing`](#inherit-box-sizing) 1. [Use `unset` Instead of Resetting All Properties](#use-unset-instead-of-resetting-all-properties) 1. [Use `:not()` to Apply/Unapply Borders on Navigation](#use-not-to-applyunapply-borders-on-navigation) 1. [Check if Font Is Installed Locally](#check-if-font-is-installed-locally) 1. [Add `line-height` to `body`](#add-line-height-to-body) 1. [Set `:focus` for Form Elements](#set-focus-for-form-elements) 1. [Vertically-Center Anything](#vertically-center-anything) 1. [Use `aspect-ratio` Instead of Height/Width](#use-aspect-ratio-instead-of-heightwidth) 1. [Comma-Separated Lists](#comma-separated-lists) 1. [Select Items Using Negative `nth-child`](#select-items-using-negative-nth-child) 1. [Use SVG for Icons](#use-svg-for-icons) 1. [Use the "Lobotomized Owl" Selector](#use-the-lobotomized-owl-selector) 1. [Use `max-height` for Pure CSS Sliders](#use-max-height-for-pure-css-sliders) 1. [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) 1. [Use `rem` for Global Sizing; Use `em` for Local Sizing](#use-rem-for-global-sizing-use-em-for-local-sizing) 1. [Hide Autoplay Videos That Aren't Muted](#hide-autoplay-videos-that-arent-muted) 1. [Use `:root` for Flexible Type](#use-root-for-flexible-type) 1. [Set `font-size` on Form Elements for a Better Mobile Experience](#set-font-size-on-form-elements-for-a-better-mobile-experience) 1. [Use Pointer Events to Control Mouse Events](#use-pointer-events-to-control-mouse-events) 1. [Set `display: none` on Line Breaks Used as Spacing](#set-display-none-on-line-breaks-used-as-spacing) 1. [Use `:empty` to Hide Empty HTML Elements](#use-empty-to-hide-empty-html-elements) 1. [Use `margin-inline` instead of `margin`](#use-margin-inline-instead-of-margin) ### Use a CSS Reset CSS resets help enforce style consistency across different browsers with a clean slate for styling elements. There are plenty of reset patterns to find, or you can use a more simplified reset approach: ```css *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } ``` Now elements will be stripped of margins and padding, and `box-sizing` lets you manage layouts with the CSS box model. #### [Demo](https://codepen.io/AllThingsSmitty/pen/kkrkLL) > [!TIP] > If you follow the [Inherit `box-sizing`](#inherit-box-sizing) tip below you might opt to not include the `box-sizing` property in your CSS reset. [Back to top](#contents) ### Inherit `box-sizing` Let `box-sizing` be inherited from `html`: ```css html { box-sizing: border-box; } *, *::before, *::after { box-sizing: inherit; } ``` This makes it easier to change `box-sizing` in plugins or other components that leverage other behavior. #### [Demo](https://css-tricks.com/inheriting-box-sizing-probably-slightly-better-best-practice/) [Back to top](#contents) ### Use `unset` Instead of Resetting All Properties When resetting an element's properties, it's not necessary to reset each individual property: ```css button { background: none; border: none; color: inherit; font: inherit; outline: none; padding: 0; } ``` You can specify all of an element's properties using the `all` shorthand. Setting the value to `unset` changes an element's properties to their initial values: ```css button { all: unset; } ``` [Back to top](#contents) ### Use `:not()` to Apply/Unapply Borders on Navigation Instead of putting on the border... ```css /* add border */ .nav li { border-right: 1px solid #666; } ``` ...and then taking it off the last element... ```css /* remove border */ .nav li:last-child { border-right: none; } ``` ...use the `:not()` pseudo-class to only apply to the elements you want: ```css .nav li:not(:last-child) { border-right: 1px solid #666; } ``` Here, the CSS selector is read as a human would describe it. #### [Demo](https://codepen.io/AllThingsSmitty/pen/LkymvO) [Back to top](#contents) ### Check if Font Is Installed Locally You can check if a font is installed locally before fetching it remotely, which is a good performance tip, too. ```css @font-face { font-family: "Dank Mono"; src: /* Full name */ local("Dank Mono"), /* Postscript name */ local("Dank Mono"), /* Otherwise, download it! */ url("//...a.server/fonts/DankMono.woff"); } code { font-family: "Dank Mono", system-ui-monospace; } ``` 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` You don't need to add `line-height` to each `

`, ``, _et al_. separately. Instead, add it to `body`: ```css body { line-height: 1.5; } ``` This way textual elements can inherit from `body` easily. #### [Demo](https://codepen.io/AllThingsSmitty/pen/VjbdYd) [Back to top](#contents) ### Set `:focus` for Form Elements Sighted keyboard users rely on focus to determine where keyboard events go in the page. Make focus for form elements stand out and consistent than a browser's default implementation: ```css a:focus, button:focus, input:focus, select:focus, textarea:focus { box-shadow: none; outline: #000 dotted 2px; outline-offset: 0.05em; } ``` #### [Demo](https://codepen.io/AllThingsSmitty/pen/ePzoOP/) [Back to top](#contents) ### Vertically-Center Anything No, it's not black magic, you really can center elements vertically. You can do this with flexbox... ```css html, body { height: 100%; } body { align-items: center; display: flex; justify-content: center; } ``` ...and also with CSS Grid: ```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) [Back to top](#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 Make list items look like a real, comma-separated list: ```css ul > li:not(:last-child)::after { content: ","; } ``` 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 top](#contents) ### Select Items Using Negative `nth-child` Use negative `nth-child` in CSS to select items 1 through n. ```css li { display: none; } /* select items 1 through 3 and display them */ li:nth-child(-n + 3) { display: block; } ``` Or, since you've already learned a little about [using `:not()`](#use-not-to-applyunapply-borders-on-navigation), try: ```css /* select all items except the first 3 and display them */ li:not(:nth-child(-n + 3)) { display: block; } ``` #### [Demo](https://codepen.io/AllThingsSmitty/pen/WxjKZp) [Back to top](#contents) ### Use SVG for Icons There's no reason not to use SVG for icons: ```css .logo { background: url("logo.svg"); } ``` 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: ```css .no-svg .icon-only::after { content: attr(aria-label); } ``` [Back to top](#contents) ### Use the "Lobotomized Owl" Selector It may have a strange name but using the universal selector (`*`) with the adjacent sibling selector (`+`) can provide a powerful CSS capability: ```css * + * { margin-top: 1.5em; } ``` In this example, all elements in the flow of the document that follow other elements will receive `margin-top: 1.5em`. > [!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](https://codepen.io/AllThingsSmitty/pen/grRvWq) [Back to top](#contents) ### Use `max-height` for Pure CSS Sliders Implement CSS-only sliders using `max-height` with overflow hidden: ```css .slider { max-height: 200px; overflow-y: hidden; width: 300px; } .slider:hover { max-height: 600px; overflow-y: scroll; } ``` The element expands to the `max-height` value on hover and the slider displays as a result of the overflow. [Back to top](#contents) ### Equal-Width Table Cells Tables can be a pain to work with. Try using `table-layout: fixed` to keep cells at equal width: ```css .calendar { table-layout: fixed; } ``` Pain-free table layouts. #### [Demo](https://codepen.io/AllThingsSmitty/pen/jALALm) [Back to top](#contents) ### Get Rid of Margin Hacks With Flexbox When working with column gutters you can get rid of `nth-`, `first-`, and `last-child` hacks by using flexbox's `space-between` property: ```css .list { display: flex; justify-content: space-between; } .list .person { flex-basis: 23%; } ``` Now column gutters always appear evenly-spaced. [Back to top](#contents) ### Use Attribute Selectors with Empty Links Display links when the `` element has no text value but the `href` attribute has a link: ```css a[href^="http"]:empty::before { content: attr(href); } ``` 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()` 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 :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; } ``` #### [Demo](https://codepen.io/AllThingsSmitty/pen/rNRVxdx) [Back to top](#contents) ### Style "Default" Links Add a style for "default" links: ```css a[href]:not([class]) { color: #008000; text-decoration: underline; } ``` 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 To create a box with an intrinsic ratio, all you need to do is apply top or bottom padding to a 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%; } ``` 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](https://codepen.io/AllThingsSmitty/pen/jALZvE) [Back to top](#contents) ### Style Broken Images Make broken images more aesthetically-pleasing with a little bit of CSS: ```css img { display: block; font-family: sans-serif; font-weight: 300; height: auto; line-height: 2; position: relative; text-align: center; width: 100%; } ``` Now add pseudo-elements rules to display a user message and URL reference of the broken image: ```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; } ``` > [!TIP] > Learn more about styling for this pattern in [Ire Aderinokun's post](http://bitsofco.de/styling-broken-images/). [Back to top](#contents) ### Use `rem` for Global Sizing; Use `em` for Local Sizing After setting the base font size at the root (`html { font-size: 100%; }`), set the font size for textual elements to `em`: ```css h2 { font-size: 2em; } p { font-size: 1em; } ``` Then set the font-size for modules to `rem`: ```css article { font-size: 1.25rem; } aside .module { font-size: 0.9rem; } ``` Now each module becomes compartmentalized and easier to style, more maintainable, and flexible. [Back to top](#contents) ### Hide Autoplay Videos That Aren't Muted This is a great trick for a custom user stylesheet. Avoid overloading a user with sound from a video that autoplays when the page is loaded. If the sound isn't muted, don't show the video: ```css video[autoplay]:not([muted]) { display: none; } ``` Once again, we're taking advantage of using the [`:not()`](#use-not-to-applyunapply-borders-on-navigation) pseudo-class. [Back to top](#contents) ### Use `:root` for Flexible Type The type font size in a responsive layout should be able to adjust with each viewport. You can calculate the font size based on the viewport height and width using `:root`: ```css :root { font-size: calc(1vw + 1vh + 0.5vmin); } ``` Now you can utilize the `root em` unit based on the value calculated by `:root`: ```css body { font: 1rem/1.6 sans-serif; } ``` #### [Demo](https://codepen.io/AllThingsSmitty/pen/XKgOkR) [Back to top](#contents) ### Set `font-size` on Form Elements for a Better Mobile Experience To avoid mobile browsers (iOS Safari, _et al_.) from zooming in on HTML form elements when a ``-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. ================================================ FILE: translations/es-ES/README.md ================================================

light bulb icon

# Consejos Profesionales para CSS [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) Una colección de consejos para ayudarte a mejorar tus conocimientos profesionales de CSS. > Para ver otras listas geniales, echa un vistazo a la lista curada por [@sindresorhus](https://github.com/sindresorhus/) de [listas Awesome](https://github.com/sindresorhus/awesome/). ## Tabla de contenido * [Consejos Profesionales](#consejos-profesionales) * [Soporte](#soporte) * [Pautas para contribuir](../../CONTRIBUTING.md) ## Consejos Profesionales 1. [Utilizar un CSS Reset](#utilizar-un-css-reset) 1. [Heredar `box-sizing`](#heredar-box-sizing) 1. [Utilice `unset` en lugar de restablecer todas las propiedades](#utilice-unset-en-lugar-de-restablecer-todas-las-propiedades) 1. [Usar `:not()` para Aplicar o Cancelar la aplicación de bordes en la navegación](#usar-not-para-aplicar-o-cancelar-la-aplicación-de-bordes-en-la-navegación) 1. [Compruebe si la fuente está instalada localmente](#compruebe-si-la-fuente-está-instalada-localmente) 1. [Añadir `line-height` al `body`](#añadir-line-height-al-body) 1. [Establecer `:focus` para elementos de formulario](#establecer-focus-para-elementos-de-formulario) 1. [Centrar cualquier cosa verticalmente](#centrar-cualquier-cosa-verticalmente) 1. [Listas separadas por comas](#listas-separadas-por-comas) 1. [Seleccionar elementos usando `nth-child` negativo](#seleccionar-elementos-usando-nth-child-negativo) 1. [Utilizar SVG para los íconos](#utilizar-svg-para-los-íconos) 1. [Utilizar la herramienta de selección "Búho lobotomizado"](#utilizar-la-herramienta-de-selección-búho-lobotomizado) 1. [Usar `max-height` para Sliders con CSS puro](#usar-max-height-para-sliders-con-css-puro) 1. [Celdas de tabla de igual ancho](#celdas-de-tabla-de-igual-ancho) 1. [Deshacerse de hacks para los márgenes en Flexbox](#deshacerse-de-hacks-para-los-márgenes-en-flexbox) 1. [Utilizar atributos como selectores en enlaces vacíos](#utilizar-atributos-como-selectores-en-enlaces-vacíos) 1. [Estilizar enlaces por defecto](#estilizar-enlaces-por-defecto) 1. [Ritmo vertical consistente](#ritmo-vertical-consistente) 1. [Cajas con proporciones intrínsecas](#cajas-con-proporciones-intrínsecas) 1. [Estilizar enlaces rotos a imágenes](#estilizar-enlaces-rotos-a-imágenes) 1. [Usar `rem` para tamaños globales; Usar `em` para tamaños locales](#usar-rem-para-tamaños-globales-usar-em-para-tamaños-locales) 1. [Esconder videos con reproducción automática que no estén silenciados](#esconder-videos-con-reproducción-automática-que-no-estén-silenciados) 1. [Utilizar `:root` para una tipografía flexible](#utilizar-root-para-una-tipografía-flexible) 1. [Definir `font-size` en los elementos de formulario para una mejor experiencia móvil](#definir-font-size-en-los-elementos-de-formulario-para-una-mejor-experiencia-móvil) 1. [Usar eventos de puntero para controlar eventos de mouse](#usar-eventos-de-puntero-para-controlar-eventos-de-mouse) 1. [Establezca `display: none` en Saltos de línea utilizados como espaciado](#establezca-display-none-en-saltos-de-línea-utilizados-como-espaciado) ### Utilizar un CSS Reset Los CSS Resets ayudan a hacer cumplir la coherencia de estilo en los diferentes navegadores, como una hoja en blanco para los elementos de estilo. Puedes utilizar una biblioteca CSS Reset como [Normalize](http://necolas.github.io/normalize.css/), y otros, o puedes utilizar un enfoque más simplificado para el reset: ```css *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } ``` Ahora los elementos están despojados de márgenes y paddings, y `box-sizing` te permite administrar el diseño con el modelo de caja de CSS. #### [Demo](http://codepen.io/AllThingsSmitty/pen/kkrkLL) **Nota:** Si sigues el consejo de más abajo [Heredar `box-sizing`](#inherit-box-sizing) puedes optar por no incluir la propiedad `box-sizing` en tu CSS reset. [volver al índice de contenidos](#tabla-de-contenido) ### Heredar `box-sizing` Heredar `box-sizing` de `html`: ```css html { box-sizing: border-box; } *, *::before, *::after { box-sizing: inherit; } ``` Esto hace que sea más fácil cambiar `box-sizing` en plugins u otros componentes que aprovechan otros comportamientos. #### [Demo](https://css-tricks.com/inheriting-box-sizing-probably-slightly-better-best-practice/) [volver al índice de contenidos](#tabla-de-contenido) ### Utilice `unset` en lugar de restablecer todas las propiedades Al restablecer las propiedades de un elemento, no es necesario restablecer cada propiedad individual: ```css button { background: none; border: none; color: inherit; font: inherit; outline: none; padding: 0; } ``` Puede especificar todas las propiedades de un elemento usando la declaraciones cortas `all`. Establecer el valor a `unset` cambia las propiedades de un elemento a sus valores iniciales: ```css button { all: unset; } ``` [volver al índice de contenidos](#tabla-de-contenido) ### Usar `:not()` para Aplicar o Cancelar la aplicación de bordes en la navegación En lugar de poner en el borde... ```css /* Agrega estilo al borde */ .nav li { border-right: 1px solid #666; } ``` ... para luego quitarlo del último elemento... ```css /* quitar estilo al borde */ .nav li:last-child { border-right: none; } ``` ... utiliza la pseudo-clase `:not()` para sólo aplicar el estilo a los elementos que deseas: ```css .nav li:not(:last-child) { border-right: 1px solid #666; } ``` El selector CSS define los bordes de la forma en que un ser humano lo describiría. #### [Demo](http://codepen.io/AllThingsSmitty/pen/LkymvO) [volver al índice de contenidos](#tabla-de-contenido) ### Compruebe si la fuente está instalada localmente Puede verificar si una fuente está instalada localmente antes de buscarla de forma remota, lo que también es un buen consejo de rendimiento. ```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; } ``` Felicitaciones a Adam Argyle por compartir este protip y [demo](https://codepen.io/argyleink/pen/VwYJpgR). [volver al índice de contenidos](#tabla-de-contenido) ### Añadir `line-height` al `body` No es necesario añadir `line-height` a cada`

`,` `, _et al_. por separado. En su lugar, agregalo al `body`: ```css body {   line-height: 1.5; } ``` De esta manera los elementos de texto pueden heredarlo fácilmente de `body`. #### [Demo](http://codepen.io/AllThingsSmitty/pen/VjbdYd) [volver al índice de contenidos](#tabla-de-contenido) ### Establecer `:focus` para elementos de formulario Los usuarios de teclado videntes confían en el enfoque para determinar dónde van los eventos del teclado en la página. Haga que el enfoque de los elementos de formulario se destaque y sea coherente con la implementación predeterminada de un navegador: ```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/) [volver al índice de contenidos](#tabla-de-contenido) ### Centrar cualquier cosa verticalmente No, no es magia negra, realmente puedes centrar elementos verticalmente: ```css html, body {   height: 100%;   margin: 0; } body {   -webkit-align-items: center;   -ms-flex-align: center;   align-items: center;   display: -webkit-flex;   display: flex; } ``` ...y también con CSS Grid: ```css body { display: grid; height: 100vh; margin: 0; place-items: center center; } ``` ¿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. #### [Demo](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) [volver al índice de contenidos](#tabla-de-contenido) ### Listas separadas por comas Hacer que los elementos de la lista se vean de forma real, separados por comas: ```css ul > li:not(:last-child)::after { content: ","; } ``` Utilice la pseudo-clase `:not()` para agregar una coma al último elemento. **Nota:** Este consejo puede no ser ideal para la accesibilidad, específicamente para lectores de pantalla. Y copiar / pegar desde el navegador no funciona con el contenido generado por CSS. Procede con precaución. [volver al índice de contenidos](#tabla-de-contenido) ### Seleccionar elementos usando `nth-child` negativo Utiliza `nth-child` negativo en CSS para seleccionar los numerales de 1 a n. ```css li { display: none; } /* seleccionar los elementos de 1 hasta 3 y muestralos */ li:nth-child(-n+3) { display: block; } ``` O bien, como ya has aprendido un poco sobre [el uso de `:not()`](# uso no-a-applyunapply-fronteras-on-navegación), trata de: ```css /* seleccionar todos los elementos excepto los 3 primeros y mostrarlos */ li:not(:nth-child(-n+3)) { display: none; } ``` Bueno, éso ha sido bastante fácil. #### [Demo](http://codepen.io/AllThingsSmitty/pen/WxjKZp) [volver al índice de contenidos](#tabla-de-contenido) ### Utilizar SVG para los íconos No hay ninguna razón para no usar SVG para los íconos: ```css .logo {   background: url("logo.svg"); } ``` SVG funciona bien para todos los tipos de resoluciones y es compatible con todos los navegadores [hasta IE9](http://caniuse.com/#search=svg). Así que olvidate de tus archivos .png, .jpg o .gif-jif-loquesea. **Nota:** Si tienes botones de íconos con SVG para usuarios no videntes y el SVG falla al cargar, esto te ayudará a mantener la accesibilidad: ```css .no-svg .icon-only::after { content: attr(aria-label); }} ``` [volver al índice de contenidos](#tabla-de-contenido) ### Utilizar la herramienta de selección "Búho lobotomizado" Puede que tenga un nombre extraño, pero utilizando el selector universal (`*`) con el selector de hermanos adyacentes (`+`) puedes proporcionar una potente capacidad de CSS: ```css * + * {   margin-top: 1.5em; } ``` En este ejemplo, todos los elementos del flujo del documento que siguen otros elementos recibirán `margin-top: 1.5em`. Para más información sobre el selector "búho lobotomizado", lee el [post de Heydon Pickering](http://alistapart.com/article/axiomatic-css-and-lobotomized-owls) en *A List Apart*. #### [Demo](http://codepen.io/AllThingsSmitty/pen/grRvWq) [volver al índice de contenidos](#tabla-de-contenido) ### Usar `max-height` para Sliders con CSS puro Implementar un slider con CSS puro utilizando `max-height` con overflow hidden. ```css .slider { max-height: 200px; overflow-y: hidden; width: 300px; } .slider:hover { max-height: 600px; overflow-y: scroll; } ``` El elemento se expande hasta el valor de `max-height` en hover y el slider se muestra como resultado del desbordamiento (overflow). [volver al índice de contenidos](#tabla-de-contenido) ### Celdas de tabla de igual ancho Las tablas pueden ser dolorosas para trabajar, por lo que se trate de usar `table-layout: fixed` para mantener las celdas con el mismo ancho: ```css .calendar {   table-layout: fixed; } ``` Diseño de tablas sin dolor. #### [Demo](http://codepen.io/AllThingsSmitty/pen/jALALm) [volver al índice de contenidos](#tabla-de-contenido) ### Deshacerse de hacks para los márgenes en Flexbox Cuando trabajas con el espaciado entre columnas puedes deshacerte de los hacks con `nth-`, `first-` y `last-child` mediante el uso de la propiedad `space-between` de Flexbox: ```css .list { display: flex; justify-content: space-between; } .list .person { flex-basis: 23%; } ``` Ahora las columnas aparecen siempre espaciadas uniformemente. [volver al índice de contenidos](#tabla-de-contenido) ### Utilizar atributos como selectores en enlaces vacíos Mostrar vínculos cuando el elemento `` no tiene un valor de texto, pero el atributo `href` tiene un enlace: ```css a[href^="http"]:empty::before { content: attr(href); } ``` Eso es bastante conveniente. #### [Demo](http://codepen.io/AllThingsSmitty/pen/zBzXRx) [volver al índice de contenidos](#tabla-de-contenido) ### Estilizar enlaces por defecto Añadir un estilo a los enlaces "por defecto": ```css a[href]:not([class]) { color: #008000; text-decoration: underline; } ``` Ahora los enlaces que se insertan a través de un CMS, que por lo general no tienen un atributo `class`, tendrán una distinción sin afectar de forma genérica la cascada. [volver al índice de contenidos](#tabla-de-contenido) ### Ritmo vertical consistente Utilice un selector universal (`*`) dentro de un elemento para crear un ritmo vertical consistente: ```ss .intro> * {   margin-bottom: 1.25rem; } ``` Un ritmo vertical consistente proporciona una estética visual que hace que el contenido sea mucho más legible. [volver al índice de contenidos](#tabla-de-contenido) ### Cajas con proporciones intrínsecas Para crear un cuadro con una proporción intrínseca, todo lo que tiene que hacer es aplicar un padding superior o inferior a un 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%; } ``` Usando un 20% de padding hace que la altura de la caja sea igual al 20% de su anchura. No importa el ancho de la ventana, el div hijo va a mantener su relación de aspecto (100% / 20% = 5: 1). #### [Demo](http://codepen.io/AllThingsSmitty/pen/jALZvE) [volver al índice de contenidos](#tabla-de-contenido) ### Estilizar enlaces rotos a imágenes Haz que las imágenes rotas sean estéticamente más agradables con un poco de CSS: ```css img { display: block; font-family: sans-serif; font-weight: 300; height: auto; line-height: 2; position: relative; text-align: center; width: 100%; } ``` Ahora añade propiedades desde los pseudo-elementos para mostrar un mensaje al usuario y una referencia de dirección URL de la imagen rota: ```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; } ``` Aprende más sobre el estilo de este patrón en [post original](http://bitsofco.de/styling-broken-images/) de [Iré Aderinokun](https://github.com/ireade/). [volver al índice de contenidos](#tabla-de-contenido) ### Usar `rem` para tamaños globales; Usar `em` para tamaños locales Después de definir el tamaño de la fuente base en la raíz (`html { font-size: 100%; }`), ajusta el tamaño de fuente para los elementos textuales con `em`: ```css h2 {   font-size: 2em; } p {   font-size: 1 em; } ``` A continuación, establezca el tamaño de fuente para los módulos con `rem`: ```css article { font-size: 1.25rem; } aside .module { font-size: .9rem; } ``` Ahora cada módulo se vuelve compartimentado y más fácil de estilizar, más fácil de mantener, y más flexible. [volver al índice de contenidos](#tabla-de-contenido) ### Esconder videos con reproducción automática que no estén silenciados Este es un gran truco para una hoja de estilo de usuario personalizada. Evita la sobrecarga de un usuario con el sonido de un vídeo que se reproduce automáticamente cuando se carga la página. Si el sonido no está silenciado, no se muestra el video: ```css video[autoplay]:not([muted]) { display: none; } ``` Una vez más, estamos tomando ventaja de usar la pseudo-clase [`:not()`](#use-not-to-applyunapply-borders-on-navigation). [volver al índice de contenidos](#tabla-de-contenido) ### Utilizar `:root` para una tipografía flexible El tamaño de tipo de letra en un diseño que responde debe ser capaz de ajustar con cada ventana. Se puede calcular el tamaño de la fuente basada en la altura y la anchura de la ventana gráfica usando `:root`: ```css :root { font-size: calc(1vw + 1vh + .5vmin); } ``` Ahora se puede utilizar la unidad de `root em` basado en el valor calculado por `:root`: ```css body { font: 1rem/1.6 sans-serif; } ``` [volver al índice de contenidos](#tabla-de-contenido) ### Definir `font-size` en los elementos de formulario para una mejor experiencia móvil Para evitar que los navegadores móviles (iOS Safari, _et al_.) hagan zoom sobre los elementos de un formulario HTML cuando un `` est touché, ajoutez `font-size` à la règle de sélection : ```css input[type="text"], input[type="number"], select, textarea { font-size: 16px; } ``` :dancer: [retour à la table des matières](#table-des-matières) ### Utiliser les Événements de Pointeur pour Contrôler les Événements de la Souris [Les événements de pointeur](https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events) vous permettent de spécifier comment la souris interagit avec l'élément qu'elle touche. Pour désactiver l'événement de pointeur par défaut sur un bouton, par exemple : ```css button:disabled { opacity: .5; pointer-events: none; } ``` C'est aussi simple que cela. [retour à la table des matières](#table-des-matières) ### Définit `display: none` sur les sauts de ligne utilisés comme espacement Comme [Harry Roberts l'a souligné](https://twitter.com/csswizardry/status/1170835532584235008), cela peut aider à empêcher les utilisateurs du système de gestion de contenu d'utiliser des sauts de ligne supplémentaires pour l'espacement: ```css br + br { display: none; } ``` [retour à la table des matières](#table-des-matières) ## Prise en charge par les navigateurs Les versions actuelles de Chrome, Firefox, Safari, et Edge. ================================================ FILE: translations/gr-GR/README.md ================================================

light bulb icon

# Εξελιγμένες συμβουλές για CSS [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) Μια συλλογή από συμβουλές για να φτάσατε τις CSS ικανότητές σας σε επαγγελματικό επίπεδο > Για άλλες ωραίες λίστες με συμβουλές δείτε την λίστα του [@sindresorhus](https://github.com/sindresorhus/) με [τέλειες λίστες](https://github.com/sindresorhus/awesome/). ## Πίνακας περιεχομένων * [Προχωρημένες Συμβουλές](#προχωρημένες-συμβουλές) * [Υποστήριξη](#υποστήριξη) * [Μεταφράσεις](../../CONTRIBUTING.md) ## Προχωρημένες Συμβουλές 1. [Χρήση μίας CSS επαναφοράς](#χρήση-μίας-CSS-επαναφοράς) 1. [Κληρονόμιση του 'box-sizing'](#κληρονόμιση-του-box-sizing) 1. [Χρήση `unset` Αντί Για Επαναφορά Όλων Των Ιδιοτήτων](#χρήση-unset-αντί-για-επαναφορά-όλων-των-ιδιοτήτων) 1. [Χρήση `:not()` για Εφαρμόσεις/Βγάλεις τα Πλαίσια κατά την Περιήγηση](#χρήση-not-για-εφαρμόσειςβγάλεις-τα-πλαίσια-κατά-την-περιήγηση) 1. [Überprüfen Sie, ob die Schriftart lokal installiert ist](#Überprüfen-sie-ob-die-schriftart-lokal-installiert-ist) 1. [Προσθήκη `line-height` στο `body`](#προσθήκη-line-height-στο-body) 1. [Θέσε `:focus` για Στοιχεία της Φόρμας](#θέσε-focus-για-στοιχεία-της-φόρμας) 1. [Κάθετο-Κεντράρισμα Όλων](#κάθετο-κεντράρισμα-όλων) 1. [Λίστες που Χωρίζονται-με-Κόμμα](#λίστες-που-χωρίζονται-με-κόμμα) 1. [Επίλογη Αντικειμένων με Χρήση Αρνητικού `nth-child`](#επίλογη-αντικειμένων-με-χρήση-αρνητικού-nth-child) 1. [Χρήση SVG για Εικονίδια](#χρήση-SVG-για-εικονίδια) 1. [Χρήση της "Λοβοτομημένης Κουκουβάγιας" για Διαλέκτη](#χρήση-της-λοβοτομημένης-κουκουβάγιας-για-διαλέκτη) 1. [Χρήση `max-height` για Αγνούς CSS Ολισθητές](#χρήση-max-height-για-αγνούς-CSS-ολισθητές) 1. [Ίσου-Πλάτους Κελία Πίνακα](#ίσου-πλάτους-κελία-πίνακα) 1. [Απέβαλλε τα Hacks των Περιθωρίων Με Flexbox](#απέβαλλε-τα-hacks-των-περιθωρίων-με-flexbox) 1. [Χρήση Επιλογής Χαρακτηριστικών με Κένα Links](#χρήση-επιλογής-χαρακτηριστικών-με-κένα-links) 1. [Δώσε στυλ στα "Προκαθορισμένα" Links](#δώσε-στυλ-στα-προκαθορισμένα-links) 1. [Εσωτερικά Κουτία Αναλογιών](#εσωτερικά-κουτία-αναλογιών) 1. [Εικόνες με Χαλασμένο Στυλ](#εικόνες-με-χαλασμένο-στυλ) 1. [Χρήση `rem` για Προσαρμογή Μεγέθους Παντού; Χρήση `em` για Τοπική Προσαρμογή Μεγέθους](#χρήση-rem-για-προσαρμογή-μεγέθους-παντού-χρήση-em-για-τοπική-προσαρμογή-μεγέθους) 1. [Απόκριψη Βίντεο με Αυτόματη Αναπαραγωγή Που Δεν Είναι σε Σίγαση](#απόκριψη-βίντεο-με-αυτόματη-αναπαραγωγή-που-δεν-είναι-σε-σίγαση) 1. [Χρήση `:root` για Ευέλικτη Γραφή](#χρήση-root-για-ευέλικτη-γραφή) 1. [Ανάθεση `font-size` στα Στοιχεία της Φόρμας για Καλύτερη Εμπειρία από Κινητό](#ανάθεση-font-size-στα-στοιχεία-της-φόρμας-για-καλύτερη-εμπειρία-από-κινητό) 1. [Χρήση Γεγονότων Δείκτη για Έλεγχο Γεγονότων του Ποντικιού](#χρήση-γεγονότων-δείκτη-για-έλεγχο-γεγονότων-του-ποντικιού) 1. [Ανάθεση `display: none` στο Τέλος των Γραμμών που Χρησιμοποιείται σαν Κενό](#ανάθεση-display-none-στο-τέλος-των-γραμμών-που-χρησιμοποιείται-σαν-κενό) ### Χρήση μίας CSS επαναφοράς Η επαναφορά του CSS βοηθάει στο στυλ αλλά καί στην σταθερότητα ανάμεσα σε διαφορετικόυς περιηγητές αναζήτησης με καθαρό πίνακα για στυλιστικά στοιχεία.Μπορείτε να χρησιμοποιήσετε μια βιβλιοθήκη CSS επαναφοράς ετσι [Normalize](http://necolas.github.io/normalize.css/), _και αλλα._, η μπορείτε να χρησιμοποιήσετε μια πιο απλοποιημένη προσέγγιση επαναφοράς: ```css *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } ``` Τωρα τα στοιχεία θα βγουν από τα περιθώρια και από την επένδυση, και το `box-sizing` σε αφήνει να διαχειριστείς τις διατάξεις με το CSS box model. #### [Demo](http://codepen.io/AllThingsSmitty/pen/kkrkLL) **Σημείωση:** Αν ακολουθήσετε την [Κληρονόμιση του 'box-sizing'](#κληρονόμιση-του-box-sizing) σαν tip θα πρέπει να μην συμπεριληφθεί το 'box-sizing' στην CSS επαναφορά. [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) ### Κληρονόμιση του 'box-sizing' Ας κληρονομιθεί το `box-sizing` από `html`: ```css html { box-sizing: border-box; } *, *::before, *::after { box-sizing: inherit; } ``` Αυτό κάνει πιο εύκολο να αλλάξει το `box-sizing` σε πρόσθετα η σε άλλα συστατικά που μοχλεύουν άλλη συμπεριφορά. #### [Démo](https://css-tricks.com/inheriting-box-sizing-probably-slightly-better-best-practice/) [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) ### Χρήση `unset` Αντί Για Επαναφορά Όλων Των Ιδιοτήτων Όταν επαναφέρεις τις ιδιότητες ενός στοιχείου δεν είναι απαραίτητο να επαναφέρεις τις ιδιότητες κάθε ξεχωριστού στοιχείου: ```css button { background: none; border: none; color: inherit; font: inherit; outline: none; padding: 0; } ``` Μπορείς να καθορίσεις όλες τις ιδιότητες ενός στοιχείου χρησιμοποιόντας το `all` στενογραφημένο. Αν θέσεις την τιμή σε `unset` άλλαζει τις ιδιότητες ενός στοιχείου στις αρχικές: ```css button { all: unset; } ``` [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) ### Χρήση `:not()` για Εφαρμόσεις/Βγάλεις τα Πλαίσια κατά την Περιήγηση Αντί να θέσεις το περιθώριο... ```css /* add border */ .nav li { border-right: 1px solid #666; } ``` ...και μετά να το βγάλεις από το τελευταίο στοιχείο... ```css /* remove border */ .nav li:last-child { border-right: none; } ``` ...χρησιμοποίησε το `:not()` μια ψευδοκλάση που εφαρμόζεται μόνο στα στοιχεία που θες: ```css .nav li:not(:last-child) { border-right: 1px solid #666; } ``` Εδώ, ο CSS επιλέκτης διαβάστηκε όπως αν το περιέγραφε ένας άνθρωπος. #### [Demo](http://codepen.io/AllThingsSmitty/pen/LkymvO) [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) ### Überprüfen Sie, ob die Schriftart lokal installiert ist Sie können überprüfen, ob eine Schriftart lokal installiert ist, bevor Sie sie remote abrufen. Dies ist auch ein guter Leistungstipp. ```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; } ``` Hutspitze an Adam Argyle für das Teilen dieses Protips und dieser [Demo](https://codepen.io/argyleink/pen/VwYJpgR). [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) ### Προσθήκη `line-height` στο `body` Δεν χρειάζεται να προσθέσεις `line-height`σε κάθε `

`, ``, _et al_. ξεχωριστά. Αντ'αυτού, πρόσθεσέ το `body`: ```css body { line-height: 1.5; } ``` Με αυτόν τον τρόπο τα στοιχεία κειμένου μπορούν να κληρονομήσουν από το `body` έυκολα. #### [Demo](http://codepen.io/AllThingsSmitty/pen/VjbdYd) [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) ### Θέσε `:focus` για Στοιχεία της Φόρμας Όσοι χρήστες έχουν όραση και χρησιμοποιούν πληκτρολογιο μπορούν να βασιστούν στην συγκέντωση για να αποφασίσουν που πηγαίνουν τα γεγονότα του πληκτρολογίου στην σελίδα.Κάντε τα στοίχεια συγκέντρωσης να ξεχωρίζουν και σταθερά σε μια προκαθορισμένη εφαρμογή του browser: ```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/) [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) ### Κάθετο-Κεντράρισμα Όλων Όχι δεν είναι μαύρη μαγεία, μπορείτε όντως να κεντράρετε τα στοιχεία κάθετα. Μπορείτε να το κάνετε αυτό με 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; } ``` ...και επίσης με CSS Grid: ```css body { display: grid; height: 100vh; margin: 0; place-items: center center; } ``` Θέλετε να κεντραρίσετε κάτι άλλο? Vertically, Κάθετα, οριζόντια...όπως θέλετε,όποτε θέλετε, παντού? Το CSS-Tricks έχει [a nice write-up](https://css-tricks.com/centering-css-complete-guide/) on doing all of that. #### [Demo](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) ### Λίστες που Χωρίζονται-με-Κόμμα Κάντε τα αντικείμενα λίστας να φαίνονται σαν πραγματικές, χωρισμένες-με-κόμμα λίστες: ```css ul > li:not(:last-child)::after { content: ","; } ``` Χρησιμοποιείστε την `:not()` ψευδοκλάση και κανένα κόμμα δεν θα προσθεθεί στο τελευταίο αντικείμενο. **Σημείωση:** Αυτο το tip μπορεί να μην είναι ιδανικό για προσβασιμότητα, ειδικά για αυτούς που διαβάζουν απο οθόνη. Και το copy/paste από τον browser δεν δουλεύει με περιεχόμενο CSS-generated.Συνεχίστε με προσοχή. [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) ### Επίλογη Αντικειμένων με Χρήση Αρνητικού `nth-child` Χρηιμοποιείστε το αρνητικό `nth-child` στην CSS για να επιλέξετε 1 αντικείμενο από τα n. ```css li { display: none; } /* select items 1 through 3 and display them */ li:nth-child(-n+3) { display: block; } ``` Η, αφού ήδη μάθατε να σχετικά με το [using `:not()`](#use-not-to-applyunapply-borders-on-navigation), δοκιμάστε: ```css /* select all items except the first 3 and display them */ li:not(:nth-child(-n+3)) { display: block; } ``` #### [Demo](http://codepen.io/AllThingsSmitty/pen/WxjKZp) [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) ### Χρήση SVG για Εικονίδια Δεν υπάρχει λόγος να μην χρησιμοποιήσετε SVG για εικονίδια: ```css .logo { background: url("logo.svg"); } ``` το SVG κλιμακώνεται ωραία με για όλους τους τύπους ανάλυσης και υποστηρίζεται από όλους του περιηγητές [back to IE9](http://caniuse.com/#search=svg). Ρίξτε τα .png, .jpg, or .gif-jif-whatev αρχεία σας. **Σημείωση:** Αν έχετε μόνο SVG εικονίδια για κουμπιά για τους χρήστες με όραση και το SVG αποτύχει να φορτωθεί, αυτό θα βοηθήσει να διατηρηθεί η προσβασιμότητα: ```css .no-svg .icon-only::after { content: attr(aria-label); } ``` [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) ### Χρήση της "Λοβοτομημένης Κουκουβάγιας" για Διαλέκτη Μπορεί να έχει περίεργο όνομα αλλά το να χρησιμοποιείς τον καθολικό επιλέκτη (`*`) μαζί με τον παρακείμενο επιλέκτη (`+`) μπορεί να παρέχει μια ισχυρή CSS δυνατότητα: ```css * + * { margin-top: 1.5em; } ``` Σε αυτό το παράδειγμα, όλα τα στοιχεία στην ροή του αρχείου που ακολουθεί άλλα στοιχεία θα παραλάβει `margin-top: 1.5em`. Για περισσότερα πάνω στον επιλέκτη της "Λοβοτομημένης Κουκουβάγιας", διαβάστε [Heydon Pickering's post](http://alistapart.com/article/axiomatic-css-and-lobotomized-owls) πάνω στο *A List Apart*. #### [Demo](http://codepen.io/AllThingsSmitty/pen/grRvWq) [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) ### Χρήση `max-height` για Αγνούς CSS Ολισθητές Εφαρμογή σε CSS-only διαφάνεις με χρήση `max-height` με την υπερχύλιση κρυμμένη: ```css .slider { max-height: 200px; overflow-y: hidden; width: 300px; } .slider:hover { max-height: 600px; overflow-y: scroll; } ``` Το στοιχείο επεκτείνεται στην `max-height` τιμή σε περίπτωση αιώρησης του δέικτη από πάνω και οι η διαφάνεια προβάλλει σας αποτέλεμα υπερχύλισης. [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) ### Ίσου-Πλάτους Κελία Πίνακα Οι πίνακες μπορεί να είναι δύσκολοι να δουλέψει κανείς. Προσπαθήστε να χρησιμοποιήσετε το `table-layout: fixed` για να διατηρίσετε τα κελία με ίδιο πλάτος: ```css .calendar { table-layout: fixed; } ``` Χωρίς-κόπο διατάξεις πινάκων. #### [Demo](http://codepen.io/AllThingsSmitty/pen/jALALm) [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) ### Απέβαλλε τα Hacks των Περιθωρίων Με Flexbox Οτάν δουλέυεις με αυλάκια στήλης μπορείς να ξεφορτοθείς το `nth-`, `first-`, και `last-child` hacks με την χρήση της ιδιότητας του flexbox `space-between` : ```css .list { display: flex; justify-content: space-between; } .list .person { flex-basis: 23%; } ``` Τώρα τα αυλάκια των στηλών φαίνονται ίσα κατανεμημένα. [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) ### Χρήση Επιλογής Χαρακτηριστικών με Κένα Links Εμφανίστε τα links όταν το `` στοιχείο δεν έχει τιμή αλλά το `href` πεδίο εχει ενα link: ```css a[href^="http"]:empty::before { content: attr(href); } ``` Αυτό είναι πολύ βολικό. #### [Demo](http://codepen.io/AllThingsSmitty/pen/zBzXRx) [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) ### Δώσε στυλ στα "Προκαθορισμένα" Links Προσθέστε στυλ στα "προκαθορισμένα" links: ```css a[href]:not([class]) { color: #008000; text-decoration: underline; } ``` Τωρα τα link που εισχωρήθηκαν μεσω CMS, που συνήθς δεν έχουν πεδίο `class` , θα διαφοροποιούνται χωρίς να επηρεάζουν την γενική αλληλουχία. [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) ### Εσωτερικά Κουτία Αναλογιών Για να φτιάξετε ενα κουτί με εσωτερική αναλογία, το μόνο που πρέπει να κάνετε είναι να εφαρμόσετε ενα top η bottom γέμισμα σε ένα div: ```css .container { height: 0; padding-bottom: 20%; position: relative; } .container div { border: 2px dashed #ddd; height: 100%; left: 0; position: absolute; top: 0; width: 100%; } ``` Το να χρησιμοποιείς το 20% του γεμίσματος κάνει το ύψος του κουτιού ίσο με 20% απο το πλάτος του. Άσχετα με το πλάτος της θέας, το παιδί div θα κρατήσει την κλίμακά του (100% / 20% = 5:1). #### [Demo](http://codepen.io/AllThingsSmitty/pen/jALZvE) [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) ### Εικόνες με Χαλασμένο Στυλ Κάντε τις χαλασμένες εικόνες πιο αισθητικά όμορφες με λίγο CSS: ```css img { display: block; font-family: sans-serif; font-weight: 300; height: auto; line-height: 2; position: relative; text-align: center; width: 100%; } ``` Τώρα προσθέστε ψευδόστοιχείων κανόνες για να εμφανίσετε ένα μύνημα χρήστη και μια αναφορά σε URL από την χαλασμένη εικόνα: ```css img::before { content: "We're sorry, the image below is broken :("; display: block; margin-bottom: 10px; } img::after { content: "(url: " attr(src) ")"; display: block; font-size: 12px; } ``` Μάθετε περισσότερα σχετικά με το στυλ για αυτό το μοτίβο στού [Ire Aderinokun](https://github.com/ireade/)'s [αρχικό ποστ](http://bitsofco.de/styling-broken-images/). [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) ### Χρήση `rem` για Προσαρμογή Μεγέθους Παντού; Χρήση `em` για Τοπική Προσαρμογή Μεγέθους Αφού θέσετε το βασικό μέγεθος γραμματοσειράς στο root (`html { font-size: 100%; }`), θέστε το μέγεθος γραμματοσειράς για στοιχεία κειμένου σε `em`: ```css h2 { font-size: 2em; } p { font-size: 1em; } ``` Έπειτα θέστε το μέγεθος γραμματοσειράς για τις ενότητες σε `rem`: ```css article { font-size: 1.25rem; } aside .module { font-size: .9rem; } ``` Τώρα κάθε ενότητα διαχωρίζεται και είναι ευκολότερο να της δώσεις στυλ, πιο συντιρίσιμη, και ευπροσάρμοστη. [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) ### Απόκριψη Βίντεο με Αυτόματη Αναπαραγωγή Που Δεν Είναι σε Σίγαση Αυτό είναι ένα ωραίο κόλπο για έναν στυλ συνιθισμένου χρήστη. Αποφυγή κατακλυσμού χρήστη με ήχους από ενα βίντεο το οποίο παίζει αυτόματα όταν φορτωθεί η σελίδα. Αν ο ήχος δεν είναι σε σίγαση, μήν δείχνεις το βίντεο: ```css video[autoplay]:not([muted]) { display: none; } ``` Για άλλη μία φορά,εκμεταλλευόμαστε την χρήση της [`:not()`](#χρήση-not-για-εφαρμόσεις-βγάλεις-τα-πλαίσια-κατά-την-περιήγηση) ψευδοκλάσης. [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) ### Χρήση `:root` για Ευέλικτη Γραφή Ο τύπος της γραμματοσειράς σε μια αποκρίσιμη διαρρύθμιση θα πρέπει να είναι ικάνος να προσαρμόζεται με κάθε θέαση. Μπορείτε να υπολογίσετε το μέγεθος γραμματοσειράς με βάση το ύψος και το πλάτος της θέασης χρησιμοποιόντας το `:root`: ```css :root { font-size: calc(1vw + 1vh + .5vmin); } ``` Τώρα μπορείτε να χρησιμοποιήσετε την `root em` μονάδα βασισμένη στην τιμή που υπολογίστηκε από το `:root`: ```css body { font: 1rem/1.6 sans-serif; } ``` #### [Demo](http://codepen.io/AllThingsSmitty/pen/XKgOkR) [πίσω στον πίνακα περιεχομένων](#πίνακας-περιεχομένων) ### Ανάθεση `font-size` στα Στοιχεία της Φόρμας για Καλύτερη Εμπειρία από Κινητό Για να αποτρέψετε τους περιηγητές των κινητών (iOS Safari, _et al_.) απο το να μεγεθύνουν στα στοιχεία της HTML φόρμας όταν ένα `` ડ્રોપ ડાઉન ટેપ થયેલ છે, ઉમેરો `font-size` to the selector rule: ```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` તરીકે વપરાયેલ લાઇન બ્રેક્સ પર સેટ કરો [હેરી રોબર્ટ્સે નિર્દેશ કર્યો](https://twitter.com/csswizardry/status/1170835532584235008), આ સીએમએસ વપરાશકર્તાઓને અંતર માટે વધારાના લાઇન બ્રેકનો ઉપયોગ કરવાથી અટકાવી શકે છે: ```css br + br { display: none; } ``` [સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) ## આધાર વર્તમાન આવૃત્તિઓ of Chrome, Firefox, Safari, અને Edge. [સામગ્રીઓના કોષ્ટકમાં પાછા](#પ્રોપ્સ) ================================================ FILE: translations/it-IT/README.md ================================================

light bulb icon

# CSS suggerimenti per esperti [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) Una collezione di dritte per aiutarti a migliorare le tue capacità con CSS. > Per altre fantastiche liste di questo tipo guarda la [lista di fantastiche liste](https://github.com/sindresorhus/awesome/) curata da [@sindresorhus](https://github.com/sindresorhus/). ## Sommario * [Suggerimenti per esperti](#suggerimenti-per-esperti) * [Supporto](#supporto) * [Linee guida per contribuire](../../CONTRIBUTING.md) ## Suggerimenti per esperti 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; } ``` Ora elementi saranno spogliati di margini e padding, e `box-sizing` consente di gestire i layout con il box model CSS. #### [Dimostrazione](http://codepen.io/AllThingsSmitty/pen/kkrkLL) **Nota:** Se si segue la punta [Eredita il `box-sizing`](#inherit-box-sizing) in basso si potrebbe optare di non includere la proprietà box-sizing nel ripristino CSS. [torna al sommario](#sommario) ### Eredita il `box-sizing` Eredita il `box-sizing` dall'elemento `html`: ```css html { box-sizing: border-box; } *, *::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 Invece di impostare il bordo... ```css /* aggiunge il bordo */ .nav li { border-right: 1px solid #666; } ``` ...e poi rimuoverlo dall'ultimo elemento... ```css /* rimuove il bordo */ .nav li:last-child { border-right: none; } ``` ...usa la pseudo classe `:not()` per applicarlo solo agli elementi che vuoi: ```css .nav li:not(:last-child) { border-right: 1px solid #666; } ``` 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` Non è necessario aggiungere `line-height` a ogni `

`,``, _et al_. separatamente. Invece, aggiungilo a `body`: ```css body { line-height: 1.5; } ``` In questo modo gli elementi di testo possono ereditare facilmente da `body`. #### [Dimostrazione](http://codepen.io/AllThingsSmitty/pen/VjbdYd) [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 { height: 100%; margin: 0; } body { -webkit-align-items: center; -ms-flex-align: center; align-items: center; display: -webkit-flex; display: flex; } ``` ...e anche con CSS Grid: ```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: ```css ul > li:not(:last-child)::after { content: ","; } ``` Usa la pseudo classe `:not()` in modo da non aggiungere la virgola all'ultimo elemento. **Nota bene:** può non essere l'ideale per garantire l'accessibilità, nello specifico per gli screen reader. Inoltre il copia/incolla dal browser non funziona con il contenuto generato mediante CSS. Procedi con attenzione. [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. ```css li { display: none; } /* seleziona gli elementi da 1 a 3 e li mostra */ li:nth-child(-n+3) { display: block; } ``` Oppure, dato che hai già imparato un po' di cose circa l'[uso di `:not()`](#use-not-to-applyunapply-borders-on-navigation), prova: ```css /* selezionare tutti gli elementi tranne i primi 3 e visualizzarli */ li:not(:nth-child(-n+3)) { display: none; } ``` Beh... era abbastanza facile. #### [Dimostrazione](http://codepen.io/AllThingsSmitty/pen/WxjKZp) [torna al sommario](#sommario) ### Usa SVG per le icone Non c'è ragione per non usare SVG per le icone: ```css .logo { background: url("logo.svg"); } ``` SVG scala molto bene a tutti i tipi di risoluzione ed è supportata in tutti i browser [fino a IE9](http://caniuse.com/#search=svg). Perciò butta i tuoi file .png, .jpg o .gif-jif-qualsiasicosa. **Nota bene:** se usi bottoni con esclusivamente grafica SVG e le icone SVG non vengono caricate, questo ti aiuterà a preservare l'accessibilità: ```css .no-svg .icon-only::after { content: attr(aria-label); } ``` [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: ```css * + * { margin-top: 1.5em; } ``` In questo esempio, tutti gli elementi nel flusso del documento che seguono altri elementi riceveranno la proprietà `margin-top: 1.5em`. Per saperne di più sul selettore detto "lobotomized owl", leggi [l'articolo di Heydon Pickering](http://alistapart.com/article/axiomatic-css-and-lobotomized-owls) su *A List Apart*. #### [Dimostrazione](http://codepen.io/AllThingsSmitty/pen/grRvWq) [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: ```css .slider { max-height: 200px; overflow-y: hidden; width: 300px; } .slider:hover { max-height: 600px; overflow-y: scroll; } ``` L'elemento si espande al valore `max-height` all'hover e lo slider diventa visibile come risultato dell'overflow. [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: ```css .calendar { table-layout: fixed; } ``` Layout con le tabelle e senza tormento. #### [Dimostrazione](http://codepen.io/AllThingsSmitty/pen/jALALm) [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: ```css .list { display: flex; justify-content: space-between; } .list .person { flex-basis: 23%; } ``` 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: ```css a[href^="http"]:empty::before { content: attr(href); } ``` Decisamente comodo. #### [Dimostrazione](http://codepen.io/AllThingsSmitty/pen/zBzXRx) [torna al sommario](#sommario) ### Styling dei link di "Default" Aggiunge uno stile per i link "default": ```css a[href]:not([class]) { color: #008000; text-decoration: underline; } ``` Ora i link inseriti mediante un CMS, che solitamente non hanno un attributo `class`, saranno distinti senza intaccare tutti gli altri in cascata. [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: ```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%; } ``` Uare un `padding` del 20% rende l'altezza del contenitore pari al 20% della sua larghezza. Non importa quale sia la larghezza della finestra, il div figlio manterrà le proporzioni stabilite (100% / 20% = 5:1). #### [Dimostrazione](http://codepen.io/AllThingsSmitty/pen/jALZvE) [torna al sommario](#sommario) ### Styling delle immagini non scaricate Rendi le immagini non scaricate più piacevoli esteticamente con un po' di CSS: ```css img { display: block; font-family: sans-serif; font-weight: 300; height: auto; line-height: 2; position: relative; text-align: center; width: 100%; } ``` Ora aggiungi le regole per gli pseudo elementi al fine di mostrare un messaggio e un riferimento URL dell'immagine non scaricata: ```css img::before { content: "Siamo spiacenti, l'immagine non è stata scaricata. :("; display: block; margin-bottom: 10px; } img::after { content: "(url: " attr(src) ")"; display: block; font-size: 12px; } ``` Ulteriori informazioni sullo styling secondo questo pattern nell'[articolo](http://bitsofco.de/styling-broken-images/) di [Ire Aderinokun](https://github.com/ireade/). [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`: ```css h2 { font-size: 2em; } p { font-size: 1em; } ``` Poi imposta il font-size per i moduli con `rem`: ```css article { font-size: 1.25rem; } aside .module { font-size: .9rem; } ``` A questo punto ogni modulo diventa compartimentalizzato, più facile da modellare, più manutenibile e più flessibile. [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: ```css video[autoplay]:not([muted]) { display: none; } ``` Ancora una volta stiamo sfruttando la pseudo classe [`:not()`](#use-not-to-applyunapply-borders-on-navigation). [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`: ```css :root { font-size: calc(1vw + 1vh + .5vmin); } ``` Adesso puoi usare l'unità basata su `root em` sul valore calcolato da `:root`: ```css body { font: 1rem/1.6 sans-serif; } ``` #### [Dimostrazione](http://codepen.io/AllThingsSmitty/pen/XKgOkR) [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) ================================================ FILE: translations/pl-PL/README.md ================================================

light bulb icon

# 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ą 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 * [Wskazówki](#Wskazowki) * [Wsparcie](#Wsparcie) * [Wskazówki dotyczące kontrybucji do tego projektu](../../CONTRIBUTING.md) ## Wskazówki 1. [Użyj resetowania CSS](#użyj-resetowania-css) 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 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. [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. [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` 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 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 * { box-sizing: border-box; margin: 0; padding: 0; } ``` 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). #### [Demonstracja](http://codepen.io/AllThingsSmitty/pen/kkrkLL) **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 ) ### Dziedziczenie `box-sizing` Niech `box-sizing` zostanie odziedziczony z `html`: ```css html { box-sizing: border-box; } *, *::before, *::after { box-sizing: inherit; } ``` 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) ### Użyj `:not()`, aby dodać/usunąć obramownie nawigacji Zamiast dodać obramowanie... ```css /* add border */ .nav li { border-right: 1px solid #666; } ``` ...a później usunąć ja z ostatniego elementu... ```css /* usuń obramowanie */ .nav li:last-child { border-right: none; } ``` ...użyj `:not()` pseudo-klasy, aby dodać obramowanie do wybranych elementów: ```css .nav li:not(:last-child) { border-right: 1px solid #666; } ``` 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 Możesz sprawdzić, czy czcionka jest zainstalowana lokalnie, przed jej zdalnym pobraniem, co również jest dobrą wskazówką dotyczącą wydajnoś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). [powrót do spisu treści](#powrót-do-spisu-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 { line-height: 1.5; } ``` 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/) [Powrót do spisu treści](#Powrót-do-spisu-treści) ### Przesuwanie w pionie Nie, to nie jest czarna magia, naprawdę możesz wyśrodkować elementy w pionie: ```css html, body { height: 100%; margin: 0; } body { -webkit-align-items: center; -ms-flex-align: center; align-items: center; display: -webkit-flex; display: flex; } ``` a także używając CSS Grid: ```css body { display: grid; height: 100vh; margin: 0; place-items: center center; } ``` 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. #### [Demonstracja](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) [Powrót do spisu treści](#Powrót-do-spisu-treści) ### Listy podzielone przecinkami Elementy listy mogą wyglądać jak prawdziwa, oddzielona przecinkami lista: ```css ul > li:not(:last-child)::after { content: ","; } ``` 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 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 nieparzyste za pomocą negatywnego `nth-child` w CSS, aby wybrać elementy od 1 do n. ```css li { display: none; } /* select items 1 through 3 and display them */ li:nth-child(-n+3) { display: block; } ``` 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 */ li:not(:nth-child(-n+3)) { display: none; } ``` To było całkiem łatwe. #### [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 jako ikon: ```css .logo { background: url("logo.svg"); } ``` SVG skaluje się dobrze dla wszystkich typów rozdzielczości i jest obsługiwany we wszystkich przeglądarkach [wróć do IE9](http://caniuse.com/#search=svg). Więc porzuć swoje pliki .png, .jpg lub .gif-jif-whatev. **Uwaga:** Jeśli masz przyciski tylko ikony SVG dla widzących użytkowników, a SVG nie załaduje się, pomoże to w utrzymaniu dostępności: ```css .no-svg .icon-only::after { content: attr(aria-label); } ``` [Powrót do spisu treści](#Powrót-do-spisu-treści) ### Użyj selektora "Lobotomized Owl" 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 * + * { margin-top: 1.5em; } ``` W tym przykładzie wszystkie elementy, które śledzą inne elementy, otrzymają `margin-top: 1.5em`. 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*. #### [Demonstracja](http://codepen.io/AllThingsSmitty/pen/grRvWq) [Powrót do spisu treści](#Powrót-do-spisu-treści) ### Użyj`max-height` (atrybutu maksymalnej wysokości) dla suwaków Pure CSS Zaimplementuj suwaki CSS używając `max-height` z ukrytym przepełnieniem: ```css .slider { max-height: 200px; overflow-y: hidden; width: 300px; } .slider:hover { max-height: 600px; overflow-y: scroll; } ``` 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) ### Komórki tabeli o równej-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 { table-layout: fixed; } ``` Widzisz jakie to proste! :) #### [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 (column gutters) możesz pozbyć się `nth-`, `first-`, i `last-child` za pomocą właściwości`space-between`: ```css .list { display: flex; justify-content: space-between; } .list .person { flex-basis: 23%; } ``` Teraz rynny kolumnowe zawsze są rozmieszczone równomiernie. [Powrót do spisu treści](#Powrót-do-spisu-treści) ### Użyj selektorów atrybutów z pustymi linkami Wyświetl linki, gdy element `` nie ma wartości tekstowej, ale atrybut `href` posiada link: ```css a[href^="http"]:empty::before { content: attr(href); } ``` To całkiem wygodne. #### [Demonstracja](http://codepen.io/AllThingsSmitty/pen/zBzXRx) [Powrót do spisu treści](#Powrót-do-spisu-treści) ### Stylizuj "domyślne" linki Dodaj styl dla "domyślnych" linków: ```css a[href]:not([class]) { color: #008000; text-decoration: underline; } ``` 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) ### Wewnętrzne proporcje bloków Aby utworzyć pola, które posiada wewnętrzne proporcje, wystarczy zastosować górny lub dolny margines do elementu 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%; } ``` 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). #### [Demonstracja](http://codepen.io/AllThingsSmitty/pen/jALZvE) [powrót do spisu treści](#powrót-do-spisu-treści ) ### Wystylizuj uszkodzone obrazy Spraw, aby uszkodzone obrazy były bardziej estetyczne z użyciem odrobiny CSS: ```css img { display: block; font-family: sans-serif; font-weight: 300; height: auto; line-height: 2; position: relative; text-align: center; width: 100%; } ``` Następnie dodaj reguły pseudoelementów, aby wyświetlić komunikat użytkownika i adres URL uszkodzonego obrazu: ```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; } ``` 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 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 h2 { font-size: 2em; } p { font-size: 1em; } ``` Następnie ustaw rozmiar czcionki dla modułów na rem`: ```css article { font-size: 1.25rem; } aside .module { font-size: .9rem; } ``` 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 ) ### 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 widea: ```css video[autoplay]:not([muted]) { display: none; } ``` Po raz kolejny wykorzystujemy pseudo-klasę [`:not()`](#use-not-to-applyunapply-borders-on-navigation) [Powrót do spisu treści](#Powrót-do-spisu-treści ### Użyj `:root` dla elastycznych typów 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 { font-size: calc(1vw + 1vh + .5vmin); } ``` Następnie możesz użyć jednostki`root em` na podstawie wartości obliczonej przez `:root`: ```css body { font: 1rem/1.6 sans-serif; } ``` #### [Demonstracja](http://codepen.io/AllThingsSmitty/pen/XKgOkR) [powrót do spisu treści](#powrót-do-spisu-treści ) ### Ustaw rozmiar czcionki w elementach formularza Aby uniknąć korzystania z przeglądarek komórkowych (iOS Safari etc.) podczas powiększania elementów formularzy HTML, po dotknięciu menu rozwijanego `` é selecionado, adicione `font-size` no seletor: ```css input[type="text"], input[type="number"], select, textarea { font-size: 16px; } ``` :dancer: [voltar ao índice](#Índice) ### Use 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. [voltar 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; } ``` [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, e Edge. [voltar ao índice](#Índice) ================================================ FILE: translations/pt-PT/README.md ================================================

light bulb icon

# CSS Protips [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) Uma coleção de dicas para aumentar as tuas habilidades no CSS. > Dá uma olhada em outras [listas fantásticas](https://github.com/sindresorhus/awesome/) mantidas por [@sindresorhus](https://github.com/sindresorhus/). ## Índice * [Protips](#protips) * [Suporte](#suporte) * [Contribuições](../../CONTRIBUTING.md) ## Protips 1. [Usa um Reset CSS](#usa-um-reset-css) 1. [Herda o `box-sizing`](#herda-o-box-sizing) 1. [Use `unset` em vez de redefinir todas as propriedades](#use-unset-em-vez-de-redefinir-todas-as-propriedades) 1. [Usa `:not()` para Aplicar/Remover Bordas](#usa-not-para-aplicarremover-bordas) 1. [Verifique se a fonte está instalada localmente](#verifique-se-a-fonte-está-instalada-localmente) 1. [Define o `line-height` no `body`](#define-o-line-height-no-body) 1. [Alinha Elementos Verticalmente](#alinha-elementos-verticalmente) 1. [Definir `:focus` para elementos de formulário](#definir-focus-para-elementos-de-formulário) 1. [Listas Separadas por Vírgula](#listas-separadas-por-vírgula) 1. [Seleciona Itens Usando `nth-child` Negativo](#seleciona-itens-usando-nth-child-negativo) 1. [Ícones SVG](#Ícones-svg) 1. [Usa o Seletor "Lobotomized Owl"](#usa-o-seletor-lobotomized-owl) 1. [Sliders em CSS com `max-height`](#sliders-em-css-com-max-height) 1. [Tabelas com Células de Tamanho Igual](#tabelas-com-células-de-tamanho-igual) 1. [Esquece as "Margin Hacks", use Flexbox](#esquece-as-margin-hacks-usa-a-flexbox) 1. [Usa Seletores de Atributo em Links Vazios](#usa-seletores-de-atributo-em-links-vazios) 1. [Estiliza Links "Default"](#estiliza-links-default) 1. [Div com Proporção de Tela Fixa](#div-com-proporção-de-tela-fixa) 1. [Estiliza Imagens Quebradas](#estiliza-imagens-quebradas) 1. [Usa `rem` para Definir Tamanhos Globais; Usa `em` para Definir Tamanhos Locais](#usa-rem-para-definir-tamanhos-globais-usa-em-para-definir-tamanhos-locais) 1. [Esconde Vídeos em Autoplay Que Não Estejam no modo Mudo](#esconde-vídeos-em-autoplay-que-não-estejam-no-mudo) 1. [Usa `:root` para uma Tipografia Flexível](#usa-root-para-uma-typografia-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) ### Usa um Reset CSS Reiniciar o CSS vai ajudar te a manter a consistência de estilo em diferentes navegadores com um ponto de partida limpo para elementos de estilo. Tu podes usar a biblioteca de reset CSS como [Normalize](http://necolas.github.io/normalize.css/), ou se preferires,adota uma abordagem mais simplificada.: ```css *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } ``` Agora os elementos estão sem margens, preenchimento e `box-sizing`.Permitindo-te gerir o layout com o teu CSS. #### [Passeata](http://codepen.io/AllThingsSmitty/pen/kkrkLL) **Nota:** Se tu seguires o guia [Herda o box-sizing](#herde-o-box-sizing) abaixo, podes optar por não incluir a propriedade `box-sizing` na tua redefinição de CSS. [Regressar ao índice](#Índice) ### Herda o `box-sizing` Faz com que o `box-sizing` seja herdado do `html`: ```css html { box-sizing: border-box; } *, *::before, *::after { box-sizing: inherit; } ``` Assim fica mais fácil de alterar o `box-sizing` em plugins ou outros componentes que tenham um comportamento diferente. #### [Passeata](https://css-tricks.com/inheriting-box-sizing-probably-slightly-better-best-practice/) [Regressar 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) ### Usa `:not()` para Aplicar/Retirar Bordas Ao invés de colocar a borda… ```css /* adiciona a borda */ .nav li { border-right: 1px solid #666; } ``` …para então retirar o último elemento… ```css /* retira a borda */ .nav li:last-child { border-right: none; } ``` …utiliza a _pseudo-class_ `:not()` para aplicar a borda apenas nos elementos corretos: ```css .nav li:not(:last-child) { border-right: 1px solid #666; } ``` O seletor CSS define a borda da maneira que um humano a descreveria. #### [Passeata](http://codepen.io/AllThingsSmitty/pen/LkymvO) [Regressar 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; } ``` Dica de chapéu para Adam Argyle por compartilhar este protip e [exemplo](https://codepen.io/argyleink/pen/VwYJpgR). [Regressar ao índice](#Índice) ### Define o `line-height` no `body` Não precisas de adicionar o `line-height` para cada `

`, ``, _et al_. separadamente. Apenas adiciona ao `body`: ```css body { line-height: 1.5; } ``` Desta forma elementos de texto vão herdar o `line-height` do `body`. #### [Passeata](http://codepen.io/AllThingsSmitty/pen/VjbdYd) [Regressar 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; } ``` #### [Passeata](https://codepen.io/AllThingsSmitty/pen/ePzoOP/) [Regressar ao índice](#Índice) ### Alinha Elementos Verticalmente Que bruxaria é essa? Não é bruxaria!Tu realmente podes centralizar elementos verticalmente: ```css html, body { height: 100%; margin: 0; } body { -webkit-align-items: center; -ms-flex-align: center; align-items: center; display: -webkit-flex; display: flex; } ``` ...e também com CSS Grid: ```css body { display: grid; height: 100vh; margin: 0; place-items: center center; } ``` 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. #### [Passeata](http://codepen.io/AllThingsSmitty/pen/GqmGqZ) [Regressar ao índice](#Índice) ### Listas Separadas por Vírgula Transforma listas normais em listas separadas por vírgula: ```css ul > li:not(:last-child)::after { content: ","; } ``` Utilize a _pseudo-class_ `:not()` para evitar que a vírgula seja adicionada depois do último item. **Aviso:** Tendo em conta acessibilidade esta dica pode não ser ideal, especialmente para utilizadores de leitores de tela. Além disso, copiar e/ou colar não funciona em conteúdo criado com CSS. Procede com cautela. [Regressar ao índice](#Índice) ### Seleciona Itens Usando `nth-child` Negativo Utilize `nth-child` negativo no CSS para selecionar itens de 1 a n. ```css li { display: none; } /* mostrar itens de 1 a 3 */ li:nth-child(-n+3) { display: block; } ``` Já que aprendeste um bocadinho sobre como usar a _pseudo-class_ [using `:not()`](#use-not-to-applyunapply-borders-on-navigation), agora podes tentar: ```css /* seleciona todos os itens, exceto o primeiro 3 e exibe-os */ li:not(:nth-child(-n+3)) { display: none; } ``` Mais fácil que isto não há. #### [Passeata](http://codepen.io/AllThingsSmitty/pen/WxjKZp) [Regressar ao índice](#Índice) ### Ícones SVG Não há motivo nenhum para não usares ícones em SVG: ```css .logo { background: url("logo.svg"); } ``` A vantagem da SVG é que o ícone fica bom em qualquer resolução, além de ter suporte amplo em todos os browsers [desde o IE9](http://caniuse.com/#search=svg). Agora podes desfazer-te dos teus arquivos .png, .jpg, ou ainda .gif-jif-qissomano. **Aviso:** Se tens botões feitos apenas com ícones SVG, a dica a seguir ajudará-te a manter a acessibilidade: ```css .no-svg .icon-only::after { content: attr(aria-label); } ``` [Regressar ao índice](#Índice) ### Usa o Seletor "Lobotomized Owl" O nome é super estranho (traduzido literalmente para:"coruja lobotomizada"), mas o seu uso do seletor universal (`*`) com o seletor adjacente (`+`) pode ser muito útil: ```css * + * { margin-top: 1.5em; } ``` Neste exemplo, todos os elementos acompanhados de outros elementos recebem `margin-top: 1.5em`. Para mais exemplos utilizando o seletor "lobotomized owl", lê [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) [Regressar ao índice](#Índice) ### Sliders em CSS com `max-height` Cria _sliders_ usando apenas CSS com `max-height` e `overflow-y: hidden`: ```css .slider { max-height: 200px; overflow-y: hidden; width: 300px; } .slider:hover { max-height: 600px; overflow-y: scroll; } ``` O elemento expandirá-se ao valor definido no `max-height` no _hover_ e terás um _slider_ devido ao uso do overflow. [Regressar ao índice](#Índice) ### Tabelas com Células de Tamanho Igual Não há nada mais chato do que trabalhar com tabelas, mas agora podes usar `table-layout: fixed` para manter as células do mesmo tamanho: ```css .calendar { table-layout: fixed; } ``` Tabelas sem dores de cabeça. #### [Passeata](http://codepen.io/AllThingsSmitty/pen/jALALm) [Regressar ao índice](#Índice) ### Esquece as "Margin Hacks", usa a Flexbox Quando definires o espaçamento entre as colunas,deixa os seletores `nth-`, `first-`, e `last-child` de lado e usa a propriedade `space-between` do flexbox: ```css .list { display: flex; justify-content: space-between; } .list .person { flex-basis: 23%; } ``` Assim as colunas ficam espaçadas uniformemente. [Regressar ao índice](#Índice) ### Usa Seletores de Atributo em Links Vazios Mostra links para `` tags vazias que possuem o atributo `href`: ```css a[href^="http"]:empty::before { content: attr(href); } ``` Mão na roda. #### [Passeata](http://codepen.io/AllThingsSmitty/pen/zBzXRx) [Regressar ao índice](#Índice) ### Estiliza Links "Default" Define estilos para links "default": ```css a[href]:not([class]) { color: #008000; text-decoration: underline; } ``` Desta forma, links que foram inseridos por CMS – que normalmente não possuem o atributo `class` – vão ser estilizados sem comprometer outros links. [Regressar ao índice](#Índice) ### Div com Proporção de Tela Fixa Para criar uma div com proporção de tela fixa, tudo que você precisa fazer é adicionar `padding` (`top` ou `bottom`) a div pai: ```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%; } ``` Se usares 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) [Regressar ao índice](#Índice) ### Estiliza Imagens Quebradas Faz com que imagens quebradas fiquem esteticamente mais agradáveis com um pouquinho de CSS: ```css img { display: block; font-family: sans-serif; font-weight: 300; height: auto; line-height: 2; position: relative; text-align: center; width: 100%; } ``` Agora adiciona regras com _pseudo-elements_ para mostrar uma mensagem e a URL da imagem quebrada: ```css img::before { content: "Desculpe, a imagem abaixo não pode ser carregada :("; display: block; margin-bottom: 10px; } img::after { content: "(url: " attr(src) ")"; display: block; font-size: 12px; } ``` Lê mais um pouco sobre como estilizar imagens quebradas no [artigo original](http://bitsofco.de/styling-broken-images/) por [Ire Aderinokun](https://github.com/ireade/). [Regressar ao índice](#Índice) ### Usa `rem` para Definir Tamanhos Globais; Usa `em` para Definir Tamanhos Locais Depois de definires o tamanho de fonte base na raíz (`html { font-size: 100%; }`), define o tamanho de fonte para elementos de texto utilizando `em`: ```css h2 { font-size: 2em; } p { font-size: 1em; } ``` Então define o tamanho da fonte de módulos utilizando `rem`: ```css article { font-size: 1.25rem; } aside .module { font-size: .9rem; } ``` Assim fica mais fácil de estilizar e manter cada módulo, além de ser flexível. [Regressar ao índice](#Índice) ### Esconde Vídeos em Autoplay Que Não Estejam no Mudo Ótima dica para uma _stylesheet_ personalizada. Evita sobrecarregar o utilizador com sons de vídeos em autoplay. Se o som não estiver no mudo, esconde o vídeo: ```css video[autoplay]:not([muted]) { display: none; } ``` E aqui está mais uma entre as muitas vantagens de usar a _pseudo-class_ [`:not()`](#use-not-to-applyunapply-borders-on-navigation). [Regressar ao índice](#Índice) ### Usa `:root` para uma Typografia Flexível O tamanho de fonte de um site _responsive_ deverá ser ajustável de acordo com cada _viewport_.Podes calcular o tamanho da fonte baseando-te na largura e na altura do _viewport_ usando `:root`: ```css :root { font-size: calc(1vw + 1vh + .5vmin); } ``` Desta forma,podes utilizar a unidade de medida `root em` baseada no valor calculado por `:root`: ```css body { font: 1rem/1.6 sans-serif; } ``` #### [Passeata](http://codepen.io/AllThingsSmitty/pen/XKgOkR) [Regressar 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 `` нажат, добавьте `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` на разрывы строк, используемые как интервалы Как отметил [Гарри Робертс](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, и Edge. [вернуться к оглавлению](#table-of-contents) ================================================ FILE: translations/vn-VN/README.md ================================================

light bulb icon

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

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

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

`。 [回目录](#目录) ### 支持情况 这些技巧适用于最新版的 Chrome, Firefox, Safari, 以及 Edge。 ================================================ FILE: translations/zh-TW/README.md ================================================

light bulb icon

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

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