CSS 总结居中的方法

参考

  1. 行内元素居中(文本,链接等)


  • text-align: center;
.container{
    width: 50%;
    border: 1px solid black;
    text-align: center;
}

此种方法可以让行内元素居中, 包括类型有inline/ inline-block/ inline-table/ flex

  • display: flex; justify-content: center;
.container{
    width: 30%;
    border: 1px solid black;
    display: flex;
    justify-content: center;
}



  1. 块级元素体居中
  • 使用flex
.container{
    width: 550px;
    height: 80px;
    border: 1px solid black;
  
    display: flex;
    justify-content: center;
    align-items: center;
}


  • 使用margin: 0 auto 实现水平居中
.container{
    width: 550px;
    height: 80px;
    border: 1px solid black;
}

.box1{
    background-color: cornflowerblue;
    width: 200px;
    height: 30px;
    margin: 0 auto;
}


  • 已知元素高度,使用position: absolute
.container{
    width: 550px;
    height: 80px;
    border: 1px solid black;
    position: relative;
    /* padding: 10px; */
}

.box1{
    background-color: cornflowerblue;
    width: 200px;
    height: 30px;
    position: absolute;
    left: 50%;
    top:50%;
    margin-top: -15px;
    margin-left: -100px;
}


  • 未知元素高度,使用transform: translateY(-50%, -50%) 实现居中
.container{
    width: 550px;
    height: 80px;
    border: 1px solid black;
    position: relative;
}

.box1{
    background-color: cornflowerblue;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容