Javascript, css 布局问题整理(垂直水平居中)

源代码链接 codeSandBox
JS代码:Parent 包裹 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>
  );
}

居中的几种实现

  1. 方法1,用margin: auto来实现

    .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. 方法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的方法,用div的宽度去计算margin

    /*情形3: 使div上下左右居中*/
    .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. 用flex布局

    /*情形4: 使用flex布局*/
    .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; */
    }
    

评论

暂无评论