css中一个元素如何在其父元素居中显示

css中一个元素如何在其父元素居中显示

水平居中
水平垂直居中

水平居中

(1)在子元素上增加margin auto(被包裹的元素不能有浮动的属性。否则的话这个属性就会失效。)

<style>
        body{margin: 0;}
        .box{
            width: 400px;
            height: 400px;
            border:1px solid red;
        }
        item{
            margin:0 auto;
            width: 100px;
            height: 100x;
            background: green;
        }
</style>
<body>
    <div class="box">
        <div class="item"></div>
     </div>
</body>

(2)这个属性在没有浮动的情况下,我们可以将其转换为inline/inline-block,然后其父元素加上text-align:center;属性就可以将其居中

<style>
        body{margin: 0;}
        .box{
            width: 400px;
            height: 400px;
            border:1px solid red;
            text-align:center;
        }
        item{
            display:inline/inline-block;
            width: 100px;
            height: 100x;
            background: green;
        }
</style>
<body>
    <div class="box">
        <div class="item"></div>
     </div>
</body>

水平垂直居中

子元素相对于父元素绝对定位,并且margin值减去自己宽高的一半(注释部分)
子元素相对于父元素绝对定位,并且margin值位auto,不受宽高限制(没注释部分)

div.son{
	display: inline-block;
	width: 50px;
	height: 50px;
	background-color: green;
	opacity: 0.5;
	position: absolute;
	/*left: 50%;
	top: 50%;
	margin-top: -25px;
	margin-left: -25px;*/
	margin: auto;
	left: 0;
	right: 0;
	top: 0;
	bottom: 0;
}

水平垂直居中

子元素相对于父元素绝对定位,并且transform: translate(-50%,-50%); 不受宽高限制(css3)

div.father{
	width: 150px;
	height: 150px;
	background-color: red;
	opacity: 0.5;
	text-indent: center;
	position: relative;
	/*margin: 0 auto;*/
}

div.son{
	/*display: inline-block;*/
	width: 50px;
	height: 50px;
	background-color: green;
	opacity: 0.5;
	position: absolute;
	left: 50%;
	top: 50%;
	transform: translate(-50%,-50%);
}

结果如下:
在这里插入图片描述

水平垂直居中

在父元素上运用CSS3的flex属性:display: flex; justify-content: center; align-items: center;

div.father{
	width: 150px;
	height: 150px;
	background-color: red;
	opacity: 0.5;
	text-indent: center;
	position: relative;
	/*margin: 0 auto;*/
	display: flex; justify-content: center; align-items: center;
}

div.son{
	/*display: inline-block;*/
	width: 50px;
	height: 50px;
	background-color: green;
	opacity: 0.5;
	position: absolute;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值