Search code examples
javascriptcssreactjstwitter-bootstrapbootstrap-4

Centered text or icon in React


Trying to place an icon at the center of two boxes. Appreciate your help on this. Thanks.


Solution

  • Because this uses bootstrap, it seems that class position-relative can be added to the container div, and position-absolute top-50 start-50 translate-middle can be added for the icon.

    Forked live demo on: codesandbox

    The posted codesandbox is using reactstrap but did not seem to install bootstrap as it requires, so the above example had the package installed.

    While the post is tagged with bootstrap-4, the installed version of reactstrap does not seem to support it, so this example had the new version of bootstrap installed. If bootstrap-4 is needed, some class names may need to be replaced as custom CSS.

    A custom class is also added for the icon to add some higher z-index:

    .custom-icon {
      z-index: 2500;
    }
    
    import "./styles.css";
    import { Row, Col, Input } from "reactstrap";
    
    export default function App() {
      return (
        <Row>
          <Col>
            <div className="input-group position-relative">
              <Input type="text" className="custom-input" placeholder="Origin" />
              <Input
                type="text"
                className="custom-input"
                placeholder="Destination"
              />
              <img
                src="https://cdn-icons-png.flaticon.com/512/1828/1828961.png"
                alt="icon"
                width="15"
                className="position-absolute top-50 start-50 translate-middle custom-icon"
              />
            </div>
          </Col>
        </Row>
      );
    }