元素水平垂直居中

一、一行文本水平和垂直居中

  • 水平居中:text-align:center
  • 垂直居中:line-height:父元素的高

二、行内元素水平和垂直居中

  • 水平居中:
    • 给父元素添加text-align:center
    • 行内元素没有脱离文档流(absolute,fixed,float)
  • 垂直居中
    • 法一:给父元素添加padding-top:((父height - 子height) / 2)px
    • 法二:给子元素添加position:absolute;top:50%;margin-top:-(子height/2)px;
  • 水平垂直居中
    • 给父元素添加text-align:centerpadding-top:((父height - 子height) / 2)px
    • 如果需要保持原有的容器高度,则父元素的高度需要减去padding-top

三、块元素的水平和垂直居中

  • 子元素或父元素加定位或者浮动或者父元素设置边框;子元素添加margin:((父height - 子height) / 2)px auto

  • 父相对子绝对

    • 法一:position + 负margin
    /*子元素添加*/
    position:absolute;
    top:50%;
    margin-top:-((子height) / 2)px;
    left:50%;
    margin-left:-((子width) / 2)px;
    
    • 法二:position + margin
    /*子元素添加*/
    position:absolute;
    margin:auto;
    left:0;
    top:0;
    right:0;
    bottom:0;
    
  • position + calc()

    #box{width: 300px;height: 300px;background: pink;position: relative;}
    #box1 {width: 100px;height: 100px;position: absolute;background-color: yellow;top: calc(50% - (子height/2)px);left:calc(50% - (子width/2)px);}
    
    <div id="box">
    	<div id="box1"></div>
    </div>
    
  • position + transform

    #box{width: 300px;height: 300px;background: pink;position: relative;}
    #box1 {width: 100px;height: 50px;background:green;position: absolute;top: 50%;left:50%;transform: translate(-50% , -50%);}
    
    <div id="box">
    	<div id="box1"></div>
    </div>
    
  • 弹性盒

    #box{width: 300px;height: 300px;background: pink;display: flex;justify-content: center;align-items: center;}
    #box1 {width: 100px;height: 50px;background:green;}
    
    <div id="box">
    	<div id="box1"></div>
    </div>
    
  • 父:table-cell 子:inline-block

#box {width: 300px;height: 300px;background: yellow;display: table-cell;vertical-align: middle;text-align: center;}
#box1 {width: 100px;height: 50px;background: green;display: inline-block;}

<div id="box">
	<div id="box1"></div>
</div>

四、表格的水平垂直居中

  • text-align: center;vertical-align: middle;

五、图片的水平垂直居中

  • 基本布局:div>img+span
  • css样式:
    • 父元素添加:text-align:center;
    • img添加:vertical-align:middle;
    • span作为参考物添加:
      • display: inline-block;
      • height: 100%;
      • vertical-align: middle;
#box{width: 300px;height: 300px;background: pink;text-align: center;}
#box img{vertical-align: middle;width: 200px;height: 200px;}
#box span{display: inline-block;height: 100%;vertical-align: middle;}

六、图片下方间隙解决办法

  • 法一:img{vertical:top / middle / bottom}
  • 法二:img{display:block}
  • 法三:img{float:left / right}
  • 法四:父元素{font-size:0}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值