居中问题(面试每日一题)

64 阅读1分钟

作者:battleKing
仓库:GithubCodePen
博客:CSDN掘金
反馈邮箱:amema@foxmail.com
特别声明:原创不易,未经授权不得转载或抄袭,如需转载可联系笔者授权

基本架构

<div class="father">
  <div class="children-div"></div>
  <text class="children-text">文字</text>
</div>
.father{
    width: 220px;
    height: 220px;
    background-color: red;
}

.children-div{
    width: 20px;
    height: 20px;
    background-color: blue;
}

常见的居中问题

  • 水平居中

    • 块元素里面的块元素<div>居中

      • 利用子元素的 margin: 0 auto 实现
      .children-div{
          margin: 0 auto;
      }
      
    • 块元素里面的行内元素 <text> 居中

      • 利用父元素的 text-align: center 实现
      .father{
          text-align: center;
      }
      
  • 垂直居中

    • 块元素里面的块元素<div>居中

      • 利用子元素的 position: absolutetransform 来实现垂直居中
      .father{
          position: relative
      }
      .children-div{
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%,-50%);
      }
      
      • 利用父元素的 flex 布局实现
      .father{
        display:flex;
        justify-content:center;
        align-tiems:center;
      }
      
    • 块元素里面的行内元素 <text> 居中

      • 利用父元素行高(line-height)= 父元素的高度(height)
      .children-text{
          line-height: 220px;
      }
      

❤️ 感谢大家

如果本文对你有帮助,就点个赞支持下吧,你的「赞」是我创作的动力。

如果你喜欢这篇文章的话,可以「点赞」 + 「收藏」 + 「转发」 给更多朋友。