css中设置居中的几种方式

1,

margin: 0 auto; //水平居中

line-height: xxpx; //区和height一样的值实现文字垂直居中

2,在子元素中设置

padding: 50px;

background-clip: content-box;

其中padding的大小为外div减内div距离除以二,用到clip是因为padding会改变元素大小?

3,巧妙利用translate,不知道为什么translate的百分比是自己而不是父元素,子元素要定位

.test{
    height: 200px;
    width: 200px;
    background-color: blue;
    color: yellow;
    position: relative;
    left: 100px;
    top: 100px;
}
.in{
    width: 100px;
    height: 100px;
    background-color: white;
    position: relative;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
}

4,利用margin和absolute定位(为什么要用到absolute呢,待我查一查)

若父子元素均用relative定位,子元素的margin-top会使影响父元素定位,若父用absolute,子用relative(或者不用),或者相反,则没问题,并且margin-top原因可能和 relative的规范有关,具体不清楚,所以当上述成立条件时,可以用具体数值,但只有子元素为absolute时且top left right bottom为0,auto才能实现居中

.test{
    height: 200px;
    width: 200px;
    background-color: blue;
    color: yellow;
    position: relative;
    left: 100px;
    top: 100px;
}
.in{
    width: 100px;
    height: 100px;
    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin:auto;
    background-color: white;
}

5,对于图片的奇技淫巧

使用一个图片占位赋予父元素大小,是的定位能够定位准确

值得注意的是,html里面的换行符会占用位置,如果不搞定的话,居中会产生奇怪的效果,并不完全居中,其奇技淫巧就是利用font-size:0;解决

囧,其实,本质问题不是换行符,是<p>标签,这个标签好像上下会有间隙,应该时换行符吧,把p改成div就没问题了‘

但是不知道为什么父元素会比子元素大4个元素,p会产生上下的超大间隙可能时换行符

<body>
    <div class="test">
        <p>
            <img src="https://gss2.bdstatic.com/-fo3dSag_xI4khGkpoWK1HF6hhy/baike/w%3D268%3Bg%3D0/sign=4a93f4b4ebcd7b89e96c3d85371f259a/0dd7912397dda14433a098ccbfb7d0a20cf48627.jpg"
            width="100px" class = "in-hide">
            <img src="https://gss2.bdstatic.com/-fo3dSag_xI4khGkpoWK1HF6hhy/baike/w%3D268%3Bg%3D0/sign=4a93f4b4ebcd7b89e96c3d85371f259a/0dd7912397dda14433a098ccbfb7d0a20cf48627.jpg"
            width="100px" class = "in-show">
        </p>
    </div>
</body>

*{
    font-size: 0;
}
.test{
    height: 200px;
    width: 200px;
    background-color: blue;
    color: yellow;
    position: absolute;
    left: 100px;
    top: 100px;
}
p{
    position: absolute;
    left: 50%;
    top: 50%;
    /*background-color: black;*/
}
.in-hide{
    visibility: hidden;
}
.in-show{
    position: absolute;
    left: -50%;
    top: -50%;
}

6,利用flex实现,略

7,和不定宽的居中有关

参考自:https://www.w3cschool.cn/css/css-center.html

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值