子元素相对父元素垂直水平居中的八种方式

客官°小女子只卖身不卖艺 2023-03-01 13:46 132阅读 0赞

基本样式

HTML

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  7. <title>Document</title>
  8. <link rel="stylesheet" href="./style.css" />
  9. </head>
  10. <body>
  11. <div id="out">
  12. <div id="inner"></div>
  13. </div>
  14. </body>
  15. </html>

CSS

  1. #out {
  2. width: 300px;
  3. height: 300px;
  4. background-color: red;
  5. }
  6. #inner {
  7. width: 50px;
  8. height: 50px;
  9. background-color: blue;
  10. }

方式一:flex

  1. #out {
  2. display: flex;
  3. justify-content: center;
  4. align-items: center;
  5. }

方式二:flex(父)+margin(子)

  1. #out{
  2. display:flex;
  3. }
  4. #inner{
  5. margin:auto;
  6. }

方式三:position + calc

  1. #out {
  2. position: relative;
  3. }
  4. #inner {
  5. position: absolute;
  6. left: calc(50% - 25px);
  7. top: calc(50% - 25px);
  8. }

方式四:position + margin

  1. #out {
  2. position: relative;
  3. border: 1px solid red;/*防止垂直方向margin重叠*/
  4. }
  5. #inner {
  6. margin-left: calc(50% - 25px);
  7. margin-top: calc(50% - 25px);
  8. }

方式五:position + margin(2)

  1. #out {
  2. position: relative;
  3. }
  4. #inner {
  5. position: absolute;
  6. top: 50%;
  7. left: 50%;
  8. margin-top: -25px;
  9. margin-left: -25px;
  10. }

方式六:position + margin(3)

  1. #out {
  2. position: relative;
  3. }
  4. #inner {
  5. top: 0;
  6. left: 0;
  7. right: 0;
  8. bottom: 0;
  9. position: absolute;
  10. margin: auto;
  11. }

方式七:position + transform

  1. #out {
  2. position: relative;
  3. }
  4. #inner {
  5. position: absolute;
  6. left: 50%;
  7. top: 50%;
  8. transform: translate(-50%, -50%);
  9. }

方式八:lineheight(父) + display:inline-block(子)

  1. #out {
  2. line-height: 325px;
  3. vertical-align: center;
  4. text-align: center;
  5. }
  6. #inner {
  7. display: inline-block;
  8. }

发表评论

表情:
评论列表 (有 0 条评论,132人围观)

还没有评论,来说两句吧...

相关阅读