CSS实现元素居中

元素内容居中

元素内容居中,如文字,可以设置水平居中和行高与容器的高度一致
text-align: center;/* 水平居中 */
line-height: 200px;/* 行高与容器一致 */

元素居中

两个盒子嵌套,使最里面盒子居中。

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

方法一:固定定位,需要固定元素大小。

用left和top将右上角定位到父元素中心,再用margin调节,也可以直接使用calc直接定位到中心

#box1{
	width: 400px;height: 400px;/* 父容器宽高 */
	border: 1px red solid;/* 边框 */
	position: relative;/* 相对定位 */
	}
#box2{
	width: 100px;height: 100px;/* 子元素 */宽高 */
	background-color: teal;/* 背景颜色 */
    position: absolute;/* 绝对定位 */
    left: calc(50% - 50px);top: calc(50% - 50px);}/* 相较于父元素位置 */

方法二:利用位移

同样使用了固定定位,再用transform: translate以自身为基准位移,适合box大小不固定

#box1{
		width: 400px;height: 400px;
		border: 1px red solid;
		position: relative;
		}
 #box2{
 		width: 100px;height: 100px;
 		background-color: teal;
        position: absolute;
        left: 50%;top: 50%;
        transform: translate(-50%,-50%);/* 向右边和上边位移自身的一半 */
        } 

方法三:上下左右全0使margin:auto生效

固定定位会使元素脱离文档流,当四个方向距离都为0时,margin:auto;会生效,从而达到居中的目的。auto:自适应。

#box1{
		width: 400px;height: 400px;
		border: 1px red solid;
		position: relative;
		}
 #box2{
 		width: 100px;height: 100px;
 		background-color: teal;
        position: absolute;
        left: 0;right: 0;top: 0; bottom: 0;/* 四边全0 */
        margin: auto;/* 自适应 */
        }

方法四:使用弹性布局

弹性盒子在一维布局中很方便,是比较常用的布局方式。可以用margin:auto;和justify-content: center;align-items: center;两种方式实现。

#box1{
		width: 400px;height: 400px;
		border: 1px red solid;
		display: flex;
	  }
 #box2{
 		width: 100px;height: 100px;
 		background-color: teal;
 		/* margin: auto; */ /* 自适应 */
 		justify-content: center;/* 水平居中 */
 		align-items: center;/* 垂直居中 */
 		}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值