Normalize (нормалайз) отзывы

Содержание

Reset CSS

Reset CSS takes a different approach and says that we don’t need the browsers’ default styles at all. Whatever styles we need, we’ll define in the project according to our needs. So “CSS Reset” resets all of the styles that come with the browser’s user agent.


This approach works well in the above example, with those to default styles: most of the time we want neither the browsers’ default nor the browser’s default .

There are multiple types of CSS Reset on the web. Here is an example of what a small part of CSS Reset looks like(from Eric Meyer’s CSS Reset):

html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed,  figure, figcaption, footer, header, hgroup,  menu, nav, output, ruby, section, summary, time, mark, audio, video {     margin: 0;     padding: 0;     border: 0;     font-size: 100%;     font: inherit;     vertical-align: baseline; }

In the CSS Reset way, we define all HTML tags to have no padding, no margin, no border, the same font-size and the same alignments.

The problem with CSS Resets is that they are ugly: they have a big chain of selectors, and they make a lot of unnecessary overrides. And even worse, they are unreadable when debugging.

CSS reset — chain of ugly CSS selectors

But still there are styles we prefer to reset like to , , and etc.

How to work, together in peace, with both Normalize CSS & CSS Reset

My suggestion to you is to use Normalize CSS with little bit of CSS Reset. Use them both, but wisely!

In my projects, I incorporate the benefits of each of the methods. On the one hand, I want the benefits of the Normalize CSS, while in other cases I want the benefits of a CSS Reset without those big chains of ugly CSS selectors.

How to use it

You can use the Sass port of Normalize in one of several methods, following the «About normalize.css» article’s suggestions:

Approach 1: Download and use normalize-scss as a starting point for your own project’s base Sass, customising the values to match the design’s requirements. (The best approach, IMO.)

  1. Copy the normalize-scss files to your sass directory so that you can alter it as you include it in your project. To aid with this method, normalize-scss includes several ready-made «fork» versions:

Approach 2: Install and include normalize-scss untouched and then build upon it, overriding the defaults later in your Sass when necessary. Just import normalize-scss like any normal Sass module by:

  1. Set variables to override the default normalize-scss variables.
  2. Import with or with (if you skipped step 2.)
  3. Output the CSS rules with

Alternatively, you can import normalize-scss immediately into your main Sass file without needing to use the mixin by:

  1. (Optionally) set variables to override the default normalize-scss variables.
  2. Import with or with (if you skipped step 2.)

Options

allowDuplicates

The option determines whether multiple, duplicate insertions of CSS libraries are allowed. By default, duplicate libraries are omitted.

postcssNormalize({ allowDuplicates: true })

forceImport

The option defines CSS libraries that will be inserted at the beginning of the CSS file. Unless overriden by , duplicate CSS libraries would still be omitted.

postcssNormalize({ forceImport: true })

Specific CSS libraries may be defined.

postcssNormalize({
  forceImport: 'sanitize.css'
})

browsers

The option defines an override of the project’s browserslist for PostCSS Normalize. This option should be avoided in leui of a browserslist file.

postcssNormalize({ browsers: 'last 2 versions' })

Putting It All Together

Utilizing the benefits of SASS pre-processor, I have a file that includes all these parts:

  • Normalize.css — the latest version of CSS Normalize from GitHub.
  • My own CSS Reset
  • A Basic Typography File

Example (_resets.scss file):

@import "resets/normalize.scss";@import "resets/reset.local.scss";@import "resets/typography.scss";

To Summarize

In this post, I showed you my CSS Architecture for Normalizing & Resetting styles, based on lots of stuff I’ve learned over the years.This post is the first in a series of articles on CSS Architecture which I will be writing and sharing with you every few weeks.

If this subject of CSS interests you, you are welcome to follow me on or medium.

My CSS Architecture Series:

  1. Normalize CSS or CSS Reset?!
  2. CSS Architecture — Folders & Files Structure
  3. CSS Architecture for Multiple Websites
  4. Naming Things in CSS

Final Words

I hope you’ve enjoyed this article and learned from my experience.If you liked this post, I would appreciate applause and sharing 🙂

More of my CSS posts:New CSS Logical Properties! CSS Position Sticky — How It Really Works!

Who Am I?I am Elad Shechter, a Web Developer specializing in CSS & HTML design and architecture. I work at Investing.com.

You can contact or follow me:My TwitterLinkedIn


You Can find me in my Facebook groups:CSS MastersCSS Masters Israel

Forms

sanitize.css includes a separate stylesheet for normalizing forms using minimal, standards-like styling.

<link href="https://unpkg.com/sanitize.css" rel="stylesheet" />
<link href="https://unpkg.com/sanitize.css/forms.css" rel="stylesheet" />
Form controls appear visually consistent and restyle consistently
button, input, select, textarea {
  background-color: transparent;
  border: 1px solid WindowFrame;
  color: inherit;
  font: inherit;
  letter-spacing: inherit;
  padding: 0.25em 0.375em;
}

,
 {
  border-width: ;
  padding: ;
}
Expandable select controls appear visually consistent
select {
  -moz-appearance: none;
  -webkit-appearance: none;
  background: no-repeat right center  1em;
  border-radius: ;
  padding-right: 1em;
}

select:not():not() {
  background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='4'%3E%3Cpath d='M4 0h6L7 4'/%3E%3C/svg%3E");
}

::-ms-expand {
  display: none;
}

Usage

Add PostCSS Normalize to your project:

npm install postcss-normalize --save-dev
{
  "browserslist": "last 2 versions"
}

Use PostCSS Normalize to process your CSS:

const postcssNormalize = require('postcss-normalize')

postcssNormalize.process(YOUR_CSS /*, processOptions, pluginOptions */)

Or use it as a PostCSS plugin:

const postcss = require('postcss')
const postcssNormalize = require('postcss-normalize')

postcss(
  postcssNormalize(/* pluginOptions */)
).process(YOUR_CSS /*, processOptions */)

PostCSS Normalize runs in all Node environments, with special instructions for:

Usage

<link href="https://unpkg.com/sanitize.css" rel="stylesheet" />

Or to exclusively support evergreen browsers.

<link href="https://unpkg.com/sanitize.css/evergreen.css" rel="stylesheet" />

Forms CSS

A separate stylesheet that normalizes form controls without side effects.

<link href="https://unpkg.com/sanitize.css/forms.css" rel="stylesheet" />

Or to exclusively support evergreen browsers.

<link href="https://unpkg.com/sanitize.css/forms.evergreen.css" rel="stylesheet" />

Assets CSS

A separate stylesheet that applies a comfortable measure to plain documents.

<link href="https://unpkg.com/sanitize.css/assets.css" rel="stylesheet" />

Typography CSS

A separate stylesheet that normalizes typography using system interface fonts.

<link href="https://unpkg.com/sanitize.css/typography.css" rel="stylesheet" />

Reduce Motion CSS

A separate stylesheet that normalizes typography using system interface fonts.

<link href="https://unpkg.com/sanitize.css/reduce-motion.css" rel="stylesheet" />

Page CSS

A separate stylesheet that applies a comfortable measure to plain documents.

<link href="https://unpkg.com/sanitize.css/page.css" rel="stylesheet" />

#Relationships and Tables

Because we’re treating a portion of our Redux store as a «database», many of the principles of database design also apply here as well. For example, if we have a many-to-many relationship, we can model that using an intermediate table that stores the IDs of the corresponding items (often known as a «join table» or an «associative table»). For consistency, we would probably also want to use the same and approach that we used for the actual item tables, like this:

Copy

{

entities{

authors { byId {}, allIds },

books { byId {}, allIds },

authorBook {

byId {

1{

id 1,

authorId 5,

bookId 22

},

2{

id 2,

authorId 5,

bookId 15,

},

3{

id 3,

authorId 42,

bookId 12

}

},

allIds 1,2,3

}

}

}

Operations like «Look up all books by this author», can then be accomplished easily with a single loop over the join table. Given the typical amounts of data in a client application and the speed of Javascript engines, this kind of operation is likely to have sufficiently fast performance for most use cases.

Reduce Motion

sanitize.css includes a separate stylesheet for restricting motion when the user has requested this at a system level.

<link href="https://unpkg.com/sanitize.css" rel="stylesheet" />
<link href="https://unpkg.com/sanitize.css/reduce-motion.css" rel="stylesheet" />
Animations, scrolling effects, and transitions are reduced in all browsers
@media (prefers-reduced-motion: reduce) {
  *,
  ::before,
  ::after {
    animation-delay: -1ms !important;
    animation-duration: 1ms !important;
    animation-iteration-count: 1 !important;
    background-attachment: initial !important;
    scroll-behavior: auto !important;
    transition-delay: 0s !important;
    transition-duration: 0s !important;
  }
}

Extended details and known issues

Additional detail and explanation of the esoteric parts of normalize.css.

Normally, using or affects the line-box height of text in all browsers. Source.

By default, Chrome on OS X and Safari on OS X allow very limited styling of , unless a border property is set. The default font weight on elements cannot safely be changed in Chrome on OSX and Safari on OS X.

It is recommended that you do not style checkbox and radio inputs as Firefox’s implementation does not respect box-sizing, padding, or width.

Certain font size values applied to number inputs cause the cursor style of the decrement button to change from to .

The search input is not fully stylable by default. In Chrome and Safari on OSX/iOS you can’t control , , , or . In Chrome and Safari on Windows you can’t control properly. It will apply but will only show a border color (which cannot be controlled) for the outer 1px of that border. Applying addresses these issues without removing the benefits of search inputs (e.g. showing past searches). Safari (but not Chrome) will clip the cancel button on when it has padding (and appearance).

The Sass port of normalize.css

This project is the Sass version of Normalize.css, a collection of HTML element and attribute rulesets to normalize styles across all browsers. This port aims to use a light dusting of Sass to make Normalize even easier to integrate with your website. To learn about why Normalize.css is so amazing, skip to the «normalize.css» section below.

This Sass port currently adds:

  • Vertical rhythm mixins: Allowing you to alter the font-size, line-height and margins in Normalize’s output without hacking the library.
  • Optional Eyeglass support.
  • Several ready-to-fork versions that integrate typography Sass modules like Typey, style guides built with KSS, or the legacy Compass module.

Normalize.css is a customisable CSS file that makes browsers render all elements more consistently and in line with modern standards.


The project relies on researching the differences between default browser styles in order to precisely target only the styles that need or benefit from normalizing.

Extended details and known issues

Additional detail and explanation of the esoteric parts of normalize.css.

By default, Chrome on OS X and Safari on OS X allow very limited styling of , unless a border property is set. The default font weight on elements cannot safely be changed in Chrome on OSX and Safari on OS X.

It is recommended that you do not style checkbox and radio inputs as Firefox’s implementation does not respect box-sizing, padding, or width.

Certain font size values applied to number inputs cause the cursor style of the decrement button to change from to .

The search input is not fully stylable by default. In Chrome and Safari on OSX/iOS you can’t control , , , or . In Chrome and Safari on Windows you can’t control properly. It will apply but will only show a border color (which cannot be controlled) for the outer 1px of that border. Applying addresses these issues without removing the benefits of search inputs (e.g. showing past searches). Safari (but not Chrome) will clip the cancel button on when it has padding (and appearance).

CSS Libraries

PostCSS Normalize can include normalize.css or sanitize.css and configure either with the following combinations:

@import "normalize"; /* also, @import "normalize.css" */
@import "normalize/opinionated"; /* also, @import "normalize.css/opinionated.css", @import "normalize.css/*" */
@import "sanitize"; /* also, @import "sanitize.css" */
@import "sanitize/forms"; /* also, @import "sanitize.css/forms.css" */
@import "sanitize/typography"; /* also, @import "sanitize.css/typography.css" */
@import "sanitize/page"; /* also, @import "sanitize.css/page.css" */
@import "sanitize/*"; /* also, @import "sanitize.css/*" (sanitize + all additions) */

Нормализовать или сбрасывать?

Стоит понимать более подробно, в чём отличие normalize.css от традиционного reset.css.

Normalize.css сохраняет полезные настройки по умолчанию

Reset.css накладывает однородный визуальный стиль, выравнивая стили по умолчанию почти для всех элементов. В отличие от этого, normalize.css сохраняет многие полезные стили браузеров по умолчанию. Это значит, что не требуется повторно объявлять стили для всех стандартных элементов типографики.

Когда элемент имеет различные стили по умолчанию в разных браузерах, normalize.css там, где это возможно, стремится сделать эти стили совместимыми и соответствующими современными стандартам.

Normalize.css исправляет популярные ошибки

Он исправляет основные баги на мобильных и десктопных устройствах, которые не затрагивает reset.css. Это включает в себя параметры отображения элементов HTML5, исправление для предварительно отформатированного текста, отображение SVG в IE9, и многие другие баги, связанные с отображаемым в разных браузерах и операционных системах.

Например, вот как normalize.css делает HTML5-элемент формы с типом кроссбраузерным и стилизованным.

Reset.css часто не приводит браузеры к тому уровню, где отправной точкой считается то, как элемент отрисовывается. Это особенно верно в отношении форм — именно здесь normalize.css может существенно помочь.

Normalize.css не мешает вашим инструментам отладки

Обычно при использовании reset.css раздражает огромная цепочка наследования свойств, которая отображается в инструментах разработчика.

Частый вид окна инструментов разработчика браузера при использовании reset.css

Такая проблема не возникает с normalize.css из-за целенаправленных стилей и умеренного использования множественных селекторов в наборе правил.

Normalize.css модульный

Проект разбит на относительно независимые участки, что позволяет увидеть, каким именно элементам нужны конкретные стили. Кроме того, это даёт вам возможность удалить блоки свойств (например, нормализацию форм), если известно, что они никогда не понадобятся на сайте.

Normalize.css имеет подробную документацию

Код normalize.css основан на детальном кроссбраузерном методичном тестировании. Подробно документированный файл вы можете найти на GitHub. Это значит, что вы можете узнать, что делает каждая строка кода, зачем она добавлена, какие различия существуют между браузерами. Также вы легко можете провести собственные тесты.

Цель проекта — показать людям, как по умолчанию браузеры отображают элементы, и помочь им упростить процесс внедрения улучшений.

CSS User Agent Styles

When a browser renders an HTML page, it applies basic styles before you’ve even written a single style. For Example, the to HTML tags in all browsers differ from the normal text: in general, their font sizes are larger, their font-weight is bold(), and they have margins on the top & the bottom.

<h1> default styles in chrome

While all browsers apply their basic styles, each browser has its specific styles different from other browsers, and that, of course, causes an inconsistency problem. That’s the problem that we’ll be talking about in this post.

The attempt to solve the browser inconsistency problem has produced two approaches: the Normalize CSS approach and the CSS Reset approach. In a nutshell, we can describe the Normalize CSS as a gentle solution and the Reset CSS as a more aggressive solution. Now let’s elaborate.

How to use it

You can use the Sass port of Normalize in one of several methods, following the «About normalize.css» article’s suggestions:

Approach 1: Download and use normalize-scss as a starting point for your own project’s base Sass, customising the values to match the design’s requirements. (The best approach, IMO.)

  1. Copy the normalize-scss files to your sass directory so that you can alter it as you include it in your project. To aid with this method, normalize-scss includes several ready-made «fork» versions: * fork-versions/default — Fork for libSass or Ruby Sass * fork-versions/deprecated-compass — Fork with Compass (deprecated) * fork-versions/typey — Fork with Typey * fork-versions/typey-chroma-kss — Fork with Typey, Chroma and KSS

Approach 2: Install and include normalize-scss untouched and then build upon it, overriding the defaults later in your Sass when necessary. Just import normalize-scss like any normal Sass module by:

  1. Set variables to override the default normalize-scss variables.
  2. Import with or with (if you skipped step 2.)
  3. Output the CSS rules with

Alternatively, you can import normalize-scss immediately into your main Sass file without needing to use the mixin by:

  1. (Optionally) set variables to override the default normalize-scss variables.
  2. Import with or with (if you skipped step 2.)

Note: if you use wiredep, normalize-scss’s bower.json points at the normalize/import-now Sass partial. If you don’t wish to immediately output the CSS, you will need to override the Sass partial that wiredep grabs from normalize-scss.

Typography

sanitize.css includes a separate stylesheet for normalizing typography using system interface fonts.

<link href="https://unpkg.com/sanitize.css" rel="stylesheet" />
<link href="https://unpkg.com/sanitize.css/typography.css" rel="stylesheet" />
Typography uses the default system font
html {
  font-family:
    system-ui,
    /* macOS 10.11-10.12 */ -apple-system,
    /* Windows 6+ */ Segoe UI,
    /* Android 4+ */ Roboto,
    /* Ubuntu 10.10+ */ Ubuntu,
    /* Gnome 3+ */ Cantarell,
    /* KDE Plasma 5+ */ Noto Sans,
    /* fallback */ sans-serif,
    /* macOS emoji */ "Apple Color Emoji",
    /* Windows emoji */ "Segoe UI Emoji",
    /* Windows emoji */ "Segoe UI Symbol",
    /* Linux emoji */ "Noto Color Emoji";
}
Pre-formatted and code-formatted text uses the monospace system font
code, kbd, pre, samp {
  font-family:
    /* macOS 10.10+ */ Menlo,
    /* Windows 6+ */ Consolas,
    /* Android 4+ */ Roboto Mono,
    /* Ubuntu 10.10+ */ Ubuntu Monospace,
    /* KDE Plasma 5+ */ Noto Mono,
    /* KDE Plasma 4+ */ Oxygen Mono,
    /* Linux/OpenOffice fallback */ Liberation Mono,
    /* fallback */ monospace;
}

#Designing a Normalized State

The basic concepts of normalizing data are:

  • Each type of data gets its own «table» in the state.
  • Each «data table» should store the individual items in an object, with the IDs of the items as keys and the items themselves as the values.
  • Any references to individual items should be done by storing the item’s ID.
  • Arrays of IDs should be used to indicate ordering.

An example of a normalized state structure for the blog example above might look like:

Copy

{

posts {

byId {

«post1″{

id «post1»,

author «user1»,

body «……»,

comments «comment1″,»comment2»

},

«post2″{

id «post2»,

author «user2»,

body «……»,

comments «comment3″,»comment4″,»comment5»

}

},

allIds «post1″,»post2»

},

comments {

byId {

«comment1″{

id «comment1»,

author «user2»,

comment «…..»,

},

«comment2″{

id «comment2»,

author «user3»,

comment «…..»,

},

«comment3″{

id «comment3»,

author «user3»,

comment «…..»,

},

«comment4″{

id «comment4»,

author «user1»,

comment «…..»,

},

«comment5″{

id «comment5»,

author «user3»,

comment «…..»,

},

},

allIds «comment1″,»comment2″,»comment3″,»commment4″,»comment5»

},

users {

byId {

«user1″{

username «user1»,

name «User 1»,

},

«user2″{

username «user2»,

name «User 2»,

},

«user3″{

username «user3»,

name «User 3»,

}

},

allIds «user1″,»user2″,»user3»

}

}

This state structure is much flatter overall. Compared to the original nested format, this is an improvement in several ways:

  • Because each item is only defined in one place, we don’t have to try to make changes in multiple places if that item is updated.
  • The reducer logic doesn’t have to deal with deep levels of nesting, so it will probably be much simpler.
  • The logic for retrieving or updating a given item is now fairly simple and consistent. Given an item’s type and its ID, we can directly look it up in a couple simple steps, without having to dig through other objects to find it.
  • Since each data type is separated, an update like changing the text of a comment would only require new copies of the «comments > byId > comment» portion of the tree. This will generally mean fewer portions of the UI that need to update because their data has changed. In contrast, updating a comment in the original nested shape would have required updating the comment object, the parent post object, the array of all post objects, and likely have caused all of the Post components and Comment components in the UI to re-render themselves.

Note that a normalized state structure generally implies that more components are connected and each component is responsible for looking up its own data, as opposed to a few connected components looking up large amounts of data and passing all that data downwards. As it turns out, having connected parent components simply pass item IDs to connected children is a good pattern for optimizing UI performance in a React Redux application, so keeping state normalized plays a key role in improving performance.

The Sass port of normalize.css

This project is the Sass version of Normalize.css, a collection of HTML element and attribute rulesets to normalize styles across all browsers. This port aims to use a light dusting of Sass to make Normalize even easier to integrate with your website. To learn about why Normalize.css is so amazing, skip to the «normalize.css» section below.

This Sass port currently adds:

  • Vertical rhythm mixins: Allowing you to alter the font-size, line-height and margins in Normalize’s output without hacking the library.
  • Optional Eyeglass support.
  • Several ready-to-fork versions that integrate typography Sass modules like Typey, style guides built with KSS, or the legacy Compass module.

normalize.css v5

Normalize.css is a customisable CSS file that makes browsers render all elements more consistently and in line with modern standards.

The project relies on researching the differences between default browser styles in order to precisely target only the styles that need or benefit from normalizing.

#Organizing Normalized Data in State

A typical application will likely have a mixture of relational data and non-relational data. While there is no single rule for exactly how those different types of data should be organized, one common pattern is to put the relational «tables» under a common parent key, such as «entities». A state structure using this approach might look like:

Copy

{

simpleDomainData1{….},

simpleDomainData2{….},

entities {

entityType1 {….},

entityType2 {….}

},

ui {

uiSection1 {….},

uiSection2 {….}

}

}

This could be expanded in a number of ways. For example, an application that does a lot of editing of entities might want to keep two sets of «tables» in the state, one for the «current» item values and one for the «work-in-progress» item values. When an item is edited, its values could be copied into the «work-in-progress» section, and any actions that update it would be applied to the «work-in-progress» copy, allowing the editing form to be controlled by that set of data while another part of the UI still refers to the original version. «Resetting» the edit form would simply require removing the item from the «work-in-progress» section and re-copying the original data from «current» to «work-in-progress», while «applying» the edits would involve copying the values from the «work-in-progress» section to the «current» section.

Making Your Own CSS Reset

In my 13 years’ experience, I have learned that there are HTML tags you always want to reset. For example links’ color, buttons’ default styles, lists’ default, etc.

Besides the that I use, I add a with all the styles I want to override. Unlike an ordinary CSS reset, I only target specific HTML tags’ styles rather than making a big list of tags.

Here is an example of how to make your own CSS Reset:

My CSS Reset— reset.local.css

/****** Elad Shechter's RESET *******//*** box sizing border-box for all elements ***/*,*::before,*::after{box-sizing:border-box;}a{text-decoration:none; color:inherit; cursor:pointer;}button{background-color:transparent; color:inherit; border-width:0; padding:0; cursor:pointer;}figure{margin:0;}input::-moz-focus-inner {border:0; padding:0; margin:0;}ul, ol, dd{margin:0; padding:0; list-style:none;}h1, h2, h3, h4, h5, h6{margin:0; font-size:inherit; font-weight:inherit;}p{margin:0;}cite {font-style:normal;}fieldset{border-width:0; padding:0; margin:0;}

This way the CSS reset is a lot less aggressive and a lot more readable in every way you look at it.

PostCSS Import Usage

PostCSS Normalize includes a function to configure PostCSS Import and allow you to continue using the syntax.

const postcss = require('postcss')
const postcssImport = require('postcss-import')
const postcssNormalize = require('postcss-normalize')

postcss(
  postcssImport(
    postcssNormalize(
      /* pluginOptions (for PostCSS Normalize) */
    ).postcssImport(
      /* pluginOptions (for PostCSS Import) */
    )
  )
) // now you can use @import "normalize.css", etc. again

Alternatively, use or to avoid conflicts with transforms.

@import-normalize;
@import-normalize "opinionated.css";
@import-sanitize;

С этим читают