居中css

1:水平居中:通过margin:auto

                 <div class="bone"></div>
                   .bone{
            width:500px;
            height:300px;
            margin:auto;
            background-color:black;
        }

2:绝对定位居中

绝对定位的元素的位置相对于最近的已定位祖先元素,如果元素没有已定位的祖先元素,那么它的位置相对于最初的包含块。
父容器元素:position: relative

     <div class="bone1"> <div>

              .bone1{
            width: 50%;
            
              height: 50%;
            
              overflow: auto;
            
              margin: auto;
            
              position: fixed;
            
              top: 0; left: 0; bottom: 0; right: 0;
            
              z-index: 999;
              background-color:red;
              
        }

3:响应式居中

百分比宽高,最大、最小宽度均可以,加 padding 也可以

   <div class="bone2"></div>
.bone2{
            width:60%;
            height:60%;
            min-width: 400px;
            max-width: 500px;
            padding:40px;
            /* 防止溢出 */
            overflow:auto;
            margin:auto;
            position:absolute;
            top:0;left:0;bottom:0;right:0;
              background-color:red;
        }

4:flex布局居中

            .bone3{
            display:flex;
            /* 垂直居中 */
            align-items: center;
            /* 水平居中 */
            justify-content:center;
            width:100%;
            height:100%;
              background-color:red;
            
        }

缺点有些浏览器不兼容
学会这几种方法css居中很简单_w3cschool

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

友情链接更多精彩内容