Using the `css` prop to define styles in Styled Components

Sara Vieira
InstructorSara Vieira
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 2 years ago

We will learn about the css prop we have at our disposal in styled-components to change the style of a component right in the render function.

We will use this prop to override the text color of a button with the one we define in this prop.

Sara Vieira: [0:00] I have these three buttons here and let's say, for some reason, I want this button, which is this one here in the elements tab, I want this to have a different color. One thing that we can always do is come here and say style and open another one and say color and then "green," if I wanted it green. I miswrote style, so that's why nothing was happening.

[0:26] If I do this, you can see that this adds it to the element.style, which is not the best way. This is very bad if we talk in terms of maintainability to override these styles. Fortunately, styled-components give us something called the CSS prop, which allows us to do this in a cleaner way. If I say css={}, you will see that absolutely nothing happens.

[0:49] One of the things that need to happen is that this includes a either Babel plugin or a macro. I'm using create-react-app, so I support macros. I need to import styled from "styled-components/macro".

[1:01] If I do this, you'll see that this button is green, and you will also see that it just has another class. Another class has been appended to it, and it just overrode whatever it had. If I add something else...Let's say that in here, this is supposed to be important -- where is that? Where is the color? Color, color, color -- and I put important, this is obviously overridden.

[1:31] The good thing about this is that it makes your CSS way more maintainable than normal style tags, as it is possible for you to override these things, as they are just applied CSS classes.

[1:41] This is how you can use the CSS tag in styled-components with the macro.

egghead
egghead
~ 11 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today