前端中的居中问题

一、文本居中

  • 文本水平居中: text-align:center
  • 文本垂直居中:
    (1)设置line-height=父元素的height (单行文本)
    (2)通过设置padding-top、padding-bottom

二、子盒子在父盒子里实现水平居中

1.margin:0 auto

块级元素相对于页面居中。
该盒子需设置了width,不然其width默认为:auto,此时会把值为auto的margin的值改为0

2.子元素使用绝对定位方式, 以及负值的margin-left

.parent{
  position:relative;
}
.child{
  position:absolute
  width: 固定;
  left:50%
  margin-left: -0.5*宽度;
}

3.子元素使用绝对定位方式, 以及left:0;right:0;margin:0 auto

.parent{
  position:relative;
}
.child{
    position: absolute;
    width: 100px;
    height: 100px;
    left: 0;
    right: 0;
    margin: 0 auto;
    background: red;
}

4.使用flex

在父容器中设置flex属性

.parent{
  display:flex
  justify-content: center
}

使用CSS3中新增的transform属性

        .box{
            width: 200px;
            height: 200px;
            background: pink;
            position: relative;
        }
        .child{
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
            left: 50%;
            transform: translate(-50%,0);
        }

三、子盒子在父盒子里实现居中

image.png

1.子元素使用绝对定位方式, 以及负值的margin-left,margin-top

.parent{
  position:relative;
}
.child{
  position:absolute
  width: 固定;
  height:固定;
  left:50%;
  top:50%;
  margin-left: -0.5*宽度;
  margin-top: -0.5*高度;
}

2.子元素使用绝对定位方式, 以及left:0;right:0;top:0;bottom:0;margin: auto

.parent{
  position:relative;
}
.child{
    position: absolute;
    width: 100px;
    height: 100px;
    left: 0;
    right: 0;
        top:0;
        bottom:0;
    margin: auto;
    background: red;
}

3.使用flex布局

        .box{
            width: 200px;
            height: 200px;
            background: pink;
            display: flex;
            justify-content: center; //水平居中
                       align-items: center; //垂直居中
        }
        .child{
            width: 100px;
            height: 100px;
            background: red;
        }

4.使用CSS3中新增的transform属性

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

相关阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 14,712评论 1 92
  • 收听音频,戳链接,旧号itclan已暂停使用,欢迎关注微信itclanCoder公众号可收听更多音频 前言 关于网...
    itclanCoder阅读 12,550评论 3 30
  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 28,506评论 1 45
  • 一、CSS入门 1、css选择器 选择器的作用是“用于确定(选定)要进行样式设定的标签(元素)”。 有若干种形式的...
    宠辱不惊丶岁月静好阅读 5,573评论 0 6
  • 《八段锦》 八段锦功法是一套独立而完整的健身功法,起源于北宋,至今共八百多年的历史。古人把这套动作比喻为“锦”,意...
    十一是十一阅读 1,301评论 0 0

友情链接更多精彩内容