Способы добавления стилей на страницу
Для добавления стилей на веб-страницу существует несколько способов, которые различаются своими возможностями и назначением. Далее рассмотрим их подробнее.
Связанные стили
При использовании связанных стилей описание селекторов и их значений располагается в отдельном файле, как правило, с расширением css, а для связывания документа с этим файлом применяется тег
. Данный тег помещается в контейнер , как показано в примере 3.1.
Пример 3.1. Подключение связанных стилей
HTML5 CSS 2.1 IE Cr Op Sa Fx
Значение атрибута тега
— rel остаётся неизменным независимо от кода, как приведено в данном примере. Значение href задаёт путь к CSS-файлу, он может быть задан как относительно, так и абсолютно. Заметьте, что таким образом можно подключать таблицу стилей, которая находится на другом сайте.
Содержимое файла mysite.css подключаемого посредством тега
приведено в примере 3.2.
Пример 3.2. Файл со стилем
Как видно из данного примера, файл со стилем не хранит никаких данных, кроме синтаксиса CSS. В свою очередь и HTML-документ содержит только ссылку на файл со стилем, т. е. таким способом в полной мере реализуется принцип разделения кода и оформления сайта. Поэтому использование связанных стилей является наиболее универсальным и удобным методом добавления стиля на сайт. Ведь стили хранятся в одном файле, а в HTML-документах указывается только ссылка на него.
Глобальные стили
При использовании глобальных стилей свойства CSS описываются в самом документе и располагаются в заголовке веб-страницы. По своей гибкости и возможностям этот способ добавления стиля уступает предыдущему, но также позволяет хранить стили в одном месте, в данном случае прямо на той же странице с помощью контейнера
Basics
styled-components is the result of wondering how we could enhance CSS for styling React component systems. By focusing on a single use case we managed to optimize the experience for developers as well as the output for end users.
Apart from the improved experience for developers, styled-components provides:
- Automatic critical CSS: styled-components keeps track of which components are rendered on a page and injects their styles and nothing else, fully automatically. Combined with code splitting, this means your users load the least amount of code necessary.
- No class name bugs: styled-components generates unique class names for your styles. You never have to worry about duplication, overlap or misspellings.
- Easier deletion of CSS: it can be hard to know whether a class name is used somewhere in your codebase. styled-components makes it obvious, as every bit of styling is tied to a specific component. If the component is unused (which tooling can detect) and gets deleted, all its styles get deleted with it.
- Simple dynamic styling: adapting the styling of a component based on its props or a global theme is simple and intuitive without having to manually manage dozens of classes.
- Painless maintenance: you never have to hunt across different files to find the styling affecting your component, so maintenance is a piece of cake no matter how big your codebase is.
- Automatic vendor prefixing: write your CSS to the current standard and let styled-components handle the rest.
You get all of these benefits while still writing the CSS you know and love, just bound to individual components.
Installing styled-components only takes a single command and you’re ready to roll:
If you use a package manager like yarn that supports the «resolutions» package.json field, we also highly recommend you add an entry to it as well corresponding to the major version range. This helps avoid an entire class of problems that arise from multiple versions of styled-components being installed in your project.
It’s highly recommended (but not required) to also use the Babel plugin. It offers many benefits like more legible class names, server-side rendering compatibility, smaller bundles, and more.
If you’re not using a module bundler or package manager we also have a global («UMD») build hosted on the unpkg CDN. Simply add the following
Once you’ve added styled-components you will have access to the global window.styled variable.
This style of usage requires the react CDN bundles and the react-is CDN bundle to be on the page as well (before the styled-components script.)
styled-components utilises tagged template literals to style your components.
It removes the mapping between components and styles. This means that when you’re defining your styles, you’re actually creating a normal React component, that has your styles attached to it.
This example creates two simple components, a wrapper and a title, with some styles attached to it:
Hello World!
This is a live editor, so play around with the code to get a feel for what it’s like to work with styled-components!
The CSS rules are automatically vendor prefixed, styled-components takes care of that for you!
Styled components uses stylis.js package under the hood for prefixing the css rules.
For additional information about the supported prefixes in stylis.js visit their repository.
You can pass a function («interpolations») to a styled component’s template literal to adapt it based on its props.
This button component has a primary state that changes its color. When setting the primary prop to true, we are swapping out its background and text color.
Quite frequently you might want to use a component, but change it slightly for a single case. Now, you could pass in an interpolated function and change them based on some props, but that’s quite a lot of effort for overriding the styles once.
To easily make a new component that inherits the styling of another, just wrap it in the styled() constructor. Here we use the button from the last section and create a special one, extending it with some color-related styling:
We can see that the new TomatoButton still resembles Button , while we have only added two new rules.
In some cases you might want to change which tag or component a styled component renders. This is common when building a navigation bar for example, where there are a mix of anchor links and buttons but they should be styled identically.
For this situation, we have an escape hatch. You can use the «as» polymorphic prop to dynamically swap out the element that receives the styles you wrote:
This works perfectly fine with custom components too!
If you are still on an older version than v4, you can use the .withComponent or .extend API’s to achieve the same result as with the «as» prop , but note that this is discouraged as with v4 .extend was removed and .withComponent was marked as a candidate for future deprecation.
The styled method works perfectly on all of your own or any third-party component, as long as they attach the passed className prop to a DOM element.
If you are using react-native keep in mind to use style instead of className .
Note how the inputColor prop is not passed to the DOM, but type and defaultValue are. That is styled-components being smart enough to filter non-standard attributes automatically for you.
If you’re familiar with importing CSS into your components (e.g. like CSSModules) you’ll be used to doing something like this:
Because a Styled Component is the combination of the element and the rules that style it, we’d write Counter like this:
If you put selectors in without the ampersand, they will refer to children of the component.
Finally, the ampersand can be used to increase the specificity of rules on the component; this can be useful if you are dealing with a mixed styled-components and vanilla CSS environment where there might be conflicting styles:
To avoid unnecessary wrappers that just pass on some props to the rendered component, or element, you can use the .attrs constructor. It allows you to attach additional props (or «attributes») to a component.
This way you can for example attach static props to an element, or pass a third-party prop like activeClassName to React Router’s Link component. Furthermore you can also attach more dynamic props to a component. The .attrs object also takes functions, that receive the props that the component receives. The return value will be merged into the resulting props as well.
Here we render an Input component and attach some dynamic and static attributes to it:
As you can see, we get access to our newly created props in the interpolations, and the type attribute is passed down to the element.
Notice that when wrapping styled components, .attrs are applied from the innermost styled component to the outermost styled component.
This allows each wrapper to override nested uses of .attrs , similarly to how css properties defined later in a stylesheet override previous declarations.
Input ‘s .attrs are applied first, and then PasswordInput ‘s .attrs :
This is why PasswordInput is of a password type, but still uses the size attribute from Input .
CSS animations with @keyframes aren’t scoped to a single component but you still don’t want them to be global to avoid name collisions. This is why we export a keyframes helper which will generate a unique instance that you can use throughout your app:
Keyframes are not supported by react-native . Instead, use the ReactNative.Animated API.
Keyframes are lazily injected when they’re used, which is how they can be code-splitted, so you have to use the css helper for shared style fragments:
This used to work in v3 and below where we didn’t code-split keyframes. If you’re upgrading from v3, make sure that all your shared style fragments are using the css helper!
styled-components can be used with React Native in the same way and with the same import. Try this example with Snack by Expo.
Some of the differences to the web-version are, that you cannot use the keyframes and createGlobalStyle helpers since React Native doesn’t support keyframes or global styles. We will also warn you if you use media queries or nest your CSS.
In v2 we support percentages. To make this possible we need to enforce units for all shorthands. If you’re migrating to v2, a codemod is available.
If you’d prefer to just import styled-components instead of styled-components/native , you can add a resolverMainFields configuration that includes «react-native» . This used to be supported in metro by default (and currently does work in haul) but appears to have been removed at some point.
Способы добавления стилей на страницу
Для добавления стилей на веб-страницу существует несколько способов, которые различаются своими возможностями и назначением. Далее рассмотрим их подробнее.
Связанные стили
При использовании связанных стилей описание селекторов и их значений располагается в отдельном файле, как правило, с расширением css, а для связывания документа с этим файлом применяется тег
. Данный тег помещается в контейнер , как показано в примере 3.1.
Пример 3.1. Подключение связанных стилей
HTML5 CSS 2.1 IE Cr Op Sa Fx
Значение атрибута тега
— rel остаётся неизменным независимо от кода, как приведено в данном примере. Значение href задаёт путь к CSS-файлу, он может быть задан как относительно, так и абсолютно. Заметьте, что таким образом можно подключать таблицу стилей, которая находится на другом сайте.
Содержимое файла mysite.css подключаемого посредством тега
приведено в примере 3.2.
Пример 3.2. Файл со стилем
Как видно из данного примера, файл со стилем не хранит никаких данных, кроме синтаксиса CSS. В свою очередь и HTML-документ содержит только ссылку на файл со стилем, т. е. таким способом в полной мере реализуется принцип разделения кода и оформления сайта. Поэтому использование связанных стилей является наиболее универсальным и удобным методом добавления стиля на сайт. Ведь стили хранятся в одном файле, а в HTML-документах указывается только ссылка на него.
Глобальные стили
При использовании глобальных стилей свойства CSS описываются в самом документе и располагаются в заголовке веб-страницы. По своей гибкости и возможностям этот способ добавления стиля уступает предыдущему, но также позволяет хранить стили в одном месте, в данном случае прямо на той же странице с помощью контейнера
How To Isolate a div from public CSS styles?
i have some code for example here in html
if i used the following css code for styling it:
the question is : How can i prevent and isolate the tags inside the mydiv div tag from styling by the public tags style ?
5 Answers 5
CSS Cascading and Inheritance Level 3 introduces the all shorthand property and the unset keyword, which, together, allow you to achieve this conveniently.
For example, if an author specifies all: initial on an element it will block all inheritance and reset all properties, as if no rules appeared in the author, user, or user-agent levels of the cascade.
This can be useful for the root element of a «widget» included in a page, which does not wish to inherit the styles of the outer page. Note, however, that any «default» style applied to that element (such as, e.g. display: block from the UA style sheet on block elements such as
) will also be blown away.
You’ll need to apply all: initial to your div and all: unset to its descendants:
You may want to use a class on your div instead of an id, so that any rules you write to style its descendants won’t have to match or beat the high specificity used in this rule.
To be really safe, you may want to block styles on potential pseudo-element descendants too:
Alternatively, for broader browser support, you can manually attempt to do what all does by setting all known CSS properties (don’t forget the prefixed versions):
You can encourage browser support for the all shorthand property and track its adoption with these issue links:
Up-to-date browser support information for the all shorthand property is available here.