Search code examples
cssreactjsreact-bootstrap

How to rewrite a modal CSS without affecting other modals in the project?


I have a loading component that I am importing on many pages in my project in that component I am using a modal, a modal that I have rewritten some of his CSS styles in a CSS file that I imported in the component the problem that I have is that this CSS change of the modal effects other modals in my project how can I let this CSS change only related to my component modal without affecting others

my loading component

import React, {Component, PropTypes} from 'react';
import {Modal} from "react-bootstrap";
import ReactLoading from 'react-loading';
import './loading.css'



export default class Loading extends Component {
    constructor(props) {
        super(props);
        this.state = {

        };
    }




    render() {
        const {show} = this.props;
        return(
            <div >
                <Modal show={show}  className="loadingModal"  keyboard={false}>
                    <Modal.Body className="testtest">

                        <ReactLoading id="modale" type={"bubbles"} color={"#2f96a1"} height={120} width={120}  />

                    </Modal.Body>
                </Modal>
            </div>
        )
    }
}

my loading css:

.modal-backdrop.in {
    opacity: 0;
    filter: alpha(opacity=00);
}
.modal.in .modal-dialog {
    display: flex;
    justify-content: center;
    margin-top: 9%;
}

#modale{
    display: flex;
    justifyContent: 'center';
    margin: auto;
}

.testtest{
    flex: 1;
    alignItems: 'center';
    justifyContent: 'center'
}

Solution

  • If you're not using CSS modules or such, I think the best way would be to respect the cascade and always assume that the css you import will spill. To do so I would encourage you to use BEM model. With it, it could be rewritten as:

                <div>
                <Modal show={show}  className="loading-modal modal--test"  keyboard={false}>
                    <Modal.Body className="modal--test__body">
    
                        <ReactLoading id="modale" class="modal--test__content" type={"bubbles"} color={"#2f96a1"} height={120} width={120}  />
    
                    </Modal.Body>
                </Modal>
            </div>
    

    And for css:

    .modal--test .modal-backdrop.in {
        opacity: 0;
        filter: alpha(opacity=00);
    }
    .modal--test .modal.in .modal-dialog {
        display: flex;
        justify-content: center;
        margin-top: 9%;
    }
    
    /* don't use ids for css */
    .modal--test__content{
        display: flex;
        justify-content: 'center';
        margin: auto;
    }
    
    .modal--test__body{
        flex: 1;
        alignItems: 'center';
        justifyContent: 'center'
    }
    

    Naturally, this doesn't follow BEM model exactly as it would require passing classes to the internal elements. Alternatively, for scoping, you can use CSS modules.