JavaScript, CSS layout problem sorting (vertical and horizontal center)

Time:2021-6-12

Source code link codesandbox
JS code: parent package app

export default function App() {
  return (
    <div className="Parent">
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
      </div>
    </div>
  );
}

Several realization methods of center

  1. Method 1, using margin: Auto to achieve

    .Parent {
      height: 500px;
      width: 500px;
      border: 1px solid black;
    }
    .App {
      font-family: sans-serif;
      text-align: center;
      border: 1px solid red;
      width: 300px;
      height: 300px;
      margin: 0 auto;
    }
  2. Method 2: display: table; Display: table cell

    .Parent {
      **display: table;**
      height: 500px;
      width: 500px;
      border: 1px solid black;
    }
    .App {
      text-align: center;
      border: 1px solid red;
      **display: table-cell;
      vertical-align: middle;**
    }
  3. Basic method, using the width of div to calculate margin

    /*Case 3: center the div up, down, left and right*/
    .Parent {
      height: 100%;
      width: 100%;
      border: 1px solid black;
    }
    .App {
      position: absolute;
      width: 300px;
      height: 300px;
      text-align: center;
      border: 1px solid red;
      left: 50%;
      top: 50%;
      margin-left: -150px;
      margin-top: -150px;
    }
  4. Layout with Flex

    /*Case 4: use flex layout*/
    .Parent {
      height: 500px;
      width: 500px;
      border: 1px solid black;
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
    }
    .App {
      width: 300px;
      height: 50%;
      text-align: center;
      border: 1px solid red;
      /* flex: 1; */
    }