css怎么将一个盒子垂直居中呢?

html-css025

css怎么将一个盒子垂直居中呢?,第1张

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8" />

<title>test</title>

<style>

div{

width:100px

height:100px

background:green

position:absolute

top:50%

margin-top:-50px

left:50%

margin-left:-50px

}

</style>

</head>

<body>

<div></div>

</body>

</html>

垂直和水平居中,只要垂直居中的话css最后两行可以不要,如果要相对父级盒子垂直居中的话,给父级盒子设置position:relative

举个例子

<div style="width: 200pxheight: 200pxbackground: bluemargin: 0 auto"></div>

这一行直接放到body里边,他肯定是居中的。

flex居中:

<div style="display: flexjustify-content:center">

<div style="width: 200pxheight="200pxbackground: red"></div>

</div>

这个也能实现居中,当然也可以垂直居中,垂直的话display: flex后面加上flex-direction: column就可以了。

这里的分号是分隔符,最后一个样式可以不加,但只要后面有其他样式就必须要加分号,不然样式会失效。