在未知宽高度的情况设置子元素垂直水平居中

效果图:

html代码:

<div class="parent">
  <div class="child">我是子元素</div>
</div>

解决方案

     在子元素未知宽高度的情况下:

使用flex布局

            .parent{
    			width:300px;
    			height: 300px;
    			background: red;
    			display: flex;
    			justify-content: center;  //水平居中
    			align-items: center;     //垂直居中
    		}
    		.child{
    			background: blue;
    		}

使用transform

            .parent{
    			position:relative;
    			width:300px;
    			height: 300px;
    			background: red;
    			margin: auto;
    		}
    		.child{
    			background: blue;
    			position: absolute;
    			top:50%;
    			left:50%;  //这里设置top和left的值,使元素的左上角的坐标位于中心
    			transform: translate(-50%,-50%);  //translate是以左上角为中心移动,所以只需往 
                                                  上和往左个移动子元素的一半即可
    			
    		}

 父元素设置为table-cell

  

           .parent{
    			width:300px;
    			height: 300px;
    			background: red;
    			display: table-cell;
    			vertical-align: middle;  //使元素在垂直上居中
    			text-align: center;	     //使元素在水平上居中
    		}
    		.child{
    			background: blue;  	
    			display: inline-block;	
    		}

  在子元素知道宽高度下:

         使用绝对定位

         先设置为绝对定位,然后使用top和left将左上角移至中心点,然后使用margin进行移动,其中移动的距离为元素的一半

           .parent{
    		  position:relative;
    			width:300px;
    			height: 300px;
    			background: red;
    			margin: auto;
    		}
    		.child{
    			position: absolute;
    			width:200px;
    			height: 200px;
    			background: blue;
    			top:50%;
    			left: 50%;
    			margin-top: -100px;
    			margin-left: -100px;
    		}

   绝对定位和相对定位相配合     

      这个思想比较强硬,设置父元素为的定位为相对定位,然后子元素设置为绝对定位,使得子元素根据父元素进行定位,再利用margin属性进行移位(移的距离根据子元素的宽高度来设定)

           .parent{
    			position:relative;
    			width:300px;
    			height: 300px;
    			background: red;
    			margin: auto;
    		}
    		
    		.child{
    			position: absolute;
    			width:200px;
    			height: 200px;
    			background: blue;
    			margin-top:50px;
    			margin-left: 50px;
    		}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值