css 实现水平垂直居中

法一:margin负值调整(确定容器的宽和高)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Bliao</title>
</head>
	<style>
		div{
			position:absolute;
			width:500px;
			height:300px;
			top:50%;
			left:50%;
			background-color:pink;
			margin:  -150px 0 0 -250px;
		}
	</style>
<body>
	<div>liao</div>
</body>
</html>
思路就是既然已经有了元素宽度和高度,那么先绝对定位把左顶点放到中心,但我们最后的目标是把图形中点放到中心,在已有宽度高度情况下通过margin负值产生位移调整中点就行了

ps:margin负值真的是比较复杂,可参考大佬文章

https://www.cnblogs.com/fbzs/p/6373315.html

https://www.cnblogs.com/xiaohuochai/p/5314289.html

法二:css3属性

同样原理不解释,上代码

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Bliao</title>
</head>
	<style>
		div{
			position: absolute;  /* 相对定位或绝对定位均可 */   
			width:500px;   
			height:300px;   
			top: 50%;   
			left: 50%;   
			transform: translate(-50%, -50%);   
			background-color: pink;   /* 方便看效果 */
		}
	</style>
<body>
	<div>liao</div>
</body>
</html>
法三、flex布局

这个可能是本人flex学艺不精吧 在写这个博文的时候反正感觉

align-items: center和justify-content: center并未起效orz

代码

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Bliao</title>
</head>
	<style>
		.container {
			  display: flex;
  			  min-height: 100vh;
              margin: 0;
			}
		#neirong{
		    //align-items: center;
		    //justify-content: center;
		    width: 12em;
		    height: 8em;
		    margin: auto;
		    background-color: pink;
		}
	</style>
<body>
	<div class="container">
		<div id="neirong"></div>
	</div>

</body>
</html>






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值