css让一个正方形方块垂直居中

时间:2023-03-09 00:54:38
css让一个正方形方块垂直居中

这里有top和margin-top的区别,top(left,right,bottom)是绝对定位,要用position,margin-top是相对定位,相对于相邻的元素或者父元素。

代码如下:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<title>square at center</title>
<style type="text/css">
#square{
position:absolute;
top:50%;
left:50%;
margin-top:-50px;
margin-left:-50px;
width:100px;
height:100px;
background-color:red;
}
</style>
</head>
<body> <div id="square">
</div> </body>
</html>