学无先后,达者为师

网站首页 编程语言 正文

CSS解决未知高度垂直居中

作者:翼遥bingo 更新时间: 2022-07-10 编程语言

文章目录

      • 一、 未知高度元素水平居中、垂直居中的实现方式
        • 1-1 绝对定位 transform: translate(-50%,-50%)
        • 1-2 css3的flex布局
      • 二、 实现图片垂直居中
        • 2-1 flex实现图片垂直居中
        • 2-2 绝对定位实现垂直居中

一、 未知高度元素水平居中、垂直居中的实现方式

1-1 绝对定位 transform: translate(-50%,-50%)

.wrap {
	position: relative;
}
.child {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%,-50%);
}

1-2 css3的flex布局

.wrap {
	display: flex;
	justify-content: center;
}
.child {
	align-self: center;
}

二、 实现图片垂直居中

2-1 flex实现图片垂直居中

<div class="flexbox">
    <img src="1.jpg" alt="">
</div>
<style>
	.flexbox{
		width: 300px;
		height: 250px;
		background:#fff;
		display: flex;
		align-items: center
		}
.flexbox img{
		width: 100px;
		height: 100px;
		align-items: center;
	}
</style>

2-2 绝对定位实现垂直居中

<div class="posdiv">
    <img src="1.jpg" alt="">
</div>
<style>
.posdiv{
	width: 300px;
	height: 250px;
	background: #fff;
	position: relative; 
	margin:0 auto
	}
.posdiv img{
	width: 100px;
	position: absolute;
	top: 50%;
	margin-top: -50px;}
</style>

原文链接:https://blog.csdn.net/hannah2233/article/details/125658610

栏目分类
最近更新