0

If I import the full bootstrap css import 'bootstrap/dist/css/bootstrap.min.css';

Then it ruins the css for the rest of my webite so I want to scope it around the variables I need it included around (navbar stuff)

I followed the recommended answer here but it didn't seem to work.

First attempt I tried this:

.bootstrap {
   @import 'bootstrap/dist/css/bootstrap.min.css'
} 

And the second attempt I followed one of the comments that built a local stylesheet and then I did this

.bootstrap {
   @import 'scoped-twbs.css'
}

Wihch didn't work either. (By didn't work, I mean the desired css changes were not visible)

I'm working in NextJS. I have a component that looks like this.

const Navbar2 = () => {
   return (
<div className={style.bootstrap}>
<Navbar collapseOnSelect expand="lg" bg="dark" variant="dark">
  <Container>
  <Navbar.Brand href="#home">React-Bootstrap</Navbar.Brand>
  <Navbar.Toggle aria-controls="responsive-navbar-nav" />
  <Navbar.Collapse id="responsive-navbar-nav">
    <Nav className="me-auto">
      <Nav.Link href="#features">Features</Nav.Link>
      <Nav.Link href="#pricing">Pricing</Nav.Link>
      <NavDropdown title="Dropdown" id="collasible-nav-dropdown">
        <NavDropdown.Item href="#action/3.1">Action</NavDropdown.Item>
        <NavDropdown.Item href="#action/3.2">Another action</NavDropdown.Item>
        <NavDropdown.Item href="#action/3.3">Something</NavDropdown.Item>
        <NavDropdown.Divider />
        <NavDropdown.Item href="#action/3.4">Separated link</NavDropdown.Item>
      </NavDropdown>
    </Nav>
    <Nav>
      <Nav.Link href="#deets">More deets</Nav.Link>
      <Nav.Link eventKey={2} href="#memes">
        Dank memes
      </Nav.Link>
    </Nav>
  </Navbar.Collapse>
  </Container>
</Navbar>
</div>
   )
}

I'm not sure what I'm misunderstanding

financial_physician
  • 1,672
  • 1
  • 14
  • 34

1 Answers1

1

Firsly, in CSS, @import rules must precede all other types of rules, except @charset rules. Hence you cannot nest them inside a selector. Also, in CSS, you cannot actually "nest" selectors. Refer: CSS @import inside a class

However, you can do so in some CSS preprocessor like SCSS that supports them, and is also supported out of box by Next.js itself. Refer: Sass Support | Next.js

Then you just need to do something like this:

// styles/foo.module.scss

.bootstrap :global {
  @import "node_modules/bootstrap/dist/css/bootstrap";
}
// pages/index.jsx

import styles from "../styles/foo.module.scss";

const IndexPage = () => (
  <div className={styles.bootstrap}>
  ...
  </div>
);

export default IndexPage;

Note the :global switches to global scope for the current selector respective identifier. In easy words it means that without this your bootstrap classes were being hashed out. So unless they were applied like styles.navbar, they were useless. Refer: Exceptions | CSS Modules

Here is a sandbox.

brc-dd
  • 10,788
  • 3
  • 47
  • 67