如何让一个div垂直水平居中,分别用css和css3的多种方法实现

咳咳,同学,你先讲一下如何让一个div垂直水平居中,至少讲三种方法?

这句话应该也都很熟吧,面试官的基操,当然这也是css中很有代表性的一道题了,作为前端领域的专业人员,你支支吾吾地就说不过去了吧,至少应该笑着说出四五个吧~~~

在这里插入图片描述

话不多说,上方案,先看看css3之前的做法,分为知道盒子的宽高和不知道盒子的宽高两种,先看需要知道盒子的宽高的:
方案一:利用margin:auto 自动适应

<style>
.parent{
	position:relative;
	width:500px;
	height:500px;    
	background-color: aquamarine;
}
.child{
	width:200px;
	height:300px;
	background-color: bisque;
	position:absolute;
	top:0;
	bottom:0;
	left:0;
	right:0;
	margin:auto;
}
</style>

<div class="parent">
	<div class="child">哈哈哈</div>
</div>

方案二:利用定位中心偏移的方法

<style>
.parent {
    width: 200px;
    height: 300px;
    background-color: aquamarine;
    position: relative;
  }

  .child {
    width: 100px;
    height: 150px;
    background-color: bisque;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -75px;
    margin-left: -50px;
  }
</style>
  
<div class="parent">
	<div class="child">哈哈哈</div>
</div>

看看不需要知道盒子宽高的方案:
方案三:利用table-cell+inline-block

<style>
.parent{
	width:500px;
	height:500px;    
	background-color: aquamarine;
	display:table-cell;
	text-align:center;
	vertical-align:middle
}
.child{
	display:inline-block;
}
</style>

<div class="parent">
	<div class="child">哈哈哈</div>
</div>

看看css3的方案:
方案四:利用翻了下布局

<style>
.parent {
    width: 200px;
    height: 300px;
    background-color: aquamarine;
    display: flex;
    align-items: center;
    justify-content: center;
  }

.child {
  background-color: bisque;
}
</style>

<div class="parent">
	<div class="child">哈哈哈</div>
</div>

方案五:利用transform、 translate结合定位

<style>
 .parent {
    width: 200px;
    height: 300px;
    background-color: aquamarine;
    position: relative;
  }

.child {
  background-color: bisque;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>

<div class="parent">
	<div class="child">哈哈哈</div>
</div>

简记为 三定位一表格一flex

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值