当父元素没有width时,css如何使子元素水平居中

(1) text-align方法:

在父元素中加入"text-align:center;",所有子元素自然水平居中。

也正是因为会使所有子元素水平居中,所以在只需要某个子元素水平居中的情况下并不适用。

.eg{
    text-align:center;
}

(2) 浮动方法:

先让父元素左浮动50%,再让子元素右浮动50%,即可实现水平居中。

.father{
  clear: left;
  float: left;
  position: relative;
  left: 50%;       /*向右边移动宽度的50%*/
  text-align: center;
}
.sun{
  float: left;
  position: relative;
  right: 50%;      /*向左边移动宽度的50%*/
}

(3)绝对定位方法:

与浮动方法相似,不过绝对定位会影响布局,谨慎使用。

.father {
  	position: absolute;
  	left: 50%;
}
.sun {
 	float: left;
  	position: relative;		/*注意,这里不能是absolute*/
  	right: 50%;
}

(4)css3的flexbox方法:

原理在https://www.w3cplus.com/blog/666.html里面有介绍,这里直接使用即可。

.father { 
	display: -webkit-box; 
	-webkit-box-orient: horizontal; 
	-webkit-box-pack: center; 
	display: -moz-box; 
	-moz-box-orient: horizontal; 
	-moz-box-pack: center; 
	display: -o-box; 
	-o-box-orient: horizontal; 
	-o-box-pack: center; 
	display: -ms-box; 
	-ms-box-orient: horizontal;
	-ms-box-pack: center; 
	display: box; 
	box-orient: horizontal; 
	box-pack: center; 
}

(5)CSS3的fit-content方法:

“fit-content”是CSS中给“width”属性新加的一个属性值,配合margin可以实现水平居中。

.father { 
	width: -moz-fit-content; 
	width:-webkit-fit-content; 
	width: fit-content; 
	margin-left: auto; 
	margin-right: auto; 
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值