1

I'm actually having trouble doing CSS with the styled component in React. Given below is the code snippet

import React from 'react';
import { Navbar, Container, Row, Col } from 'reactstrap';
import styled from 'styled-components';

const Styles = styled.div`
  .navbar {
    background-color: black;
    position: absolute;
    bottom: 0;
    width: 100%;
  }
  .h1 {
    color: white;
  }
`;

const Footer = () => {
  return (
    <Styles>
      <Navbar>
        <Container>
          <Row>
            <Col sm={{ size: 4 }}>
              <h1>Hi</h1>
            </Col>
          </Row>
        </Container>
      </Navbar>
    </Styles>
  );
};

export default Footer;

What I want to do is to change the color of the h1 tag to white but the above custom CSS is not working. I've tried background-color too, but still the issue persists.

2 Answers 2

2

With styled-components, you shouldn't use classes for styling elements. You should use separated wrappers for components, it's the main point. I think you wanted to do something like this:

import React from 'react';
import { Navbar, Container, Row, Col } from 'reactstrap';
import styled from 'styled-components';

const StyledNavbar = styled(Navbar)`
  background-color: black;
  position: absolute;
  bottom: 0;
  width: 100%;
`;

const Header = styled.h1`
  color: white;
`;

const Footer = () => {
  return (
    <StyledNavbar>
      <Container>
        <Row>
          <Col sm={{ size: 4 }}>
            <Header>Hi</Header>
          </Col>
        </Row>
      </Container>
    </StyledNavbar>
  );
};

export default Footer;
Sign up to request clarification or add additional context in comments.

2 Comments

So is it not possible without defining another variable, i.e Header?
@Nimrod but why? It's the main point of styled-components.
1

you used .h1 the class, not h1 the tag, in your css.

https://styled-components.com/docs/basics#pseudoelements-pseudoselectors-and-nesting

5 Comments

Can you give more details on the solution please, I'm new to CSS
.h1 as a class would be something like <h1 class"h1">hi</h1>. classes are selectors /attributes on a tag. this tag is an h1
Using styled.h1 needs me to define another variable, is it not possible to define it in styled.div? I only need to change the color.
ok, I added classname='h1', but it still didn't work.
actually sorry I don't think you need another variable I'll remove that. see my comment above

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.