让内容垂直居中,是一个很重要的应用情景,在很多场合都会需要。这也是面试的时候,一些考官喜欢拿来初面的小题目。
这里,小结下让内容垂直居中的三种方式。
当然,读者如果有更好的方法,也可以提出来。
基本HTML:
<div class="big"><div class="small"></div>
</div>
基本CSS:
.big{width: 600px;height: 400px;background: #eee;
}
.small{width: 200px;height: 150px;background: #f00;
}
一、使用flex
.big{display: flex;justify-content: center;align-items: center;
}
二、使用grid
.big{display: grid;place-items:center;
}
.big{display: grid;
}
.small{place-self: center;
}
三、使用position
.big{position: relative;
}
.small{position: absolute;left:50%;top:50%;transform: translate(-50%,-50%);
}