html fixed元素的水平和垂直居中
1、定义html界面
<html>
<head>
<title>fixed 水平居中 demo</title>
</head>
<body>
<div class="fixed"></div>
</body>
</html>
2、设置css样式
.fixed{
position: fixed;
width: 100px;
height: 100px;
/* top 坐标居中 */
top: 50%;
/* left 坐标居中 */
left: 50%;
/* 由于元素的高度是100px 所以此处设置为-50px以达到整个元素上移自己高度的一半,达到垂直居中 */
margin-top: -50px;
/* 由于元素的高度是100px 所以此处设置为-50px以达到整个元素左移自己宽度的一半,达到水平居中 */
margin-left: -50px;
border: solid 1px #c5c5c5;
border-radius: 5px;
background-color: blueviolet;
}
3、整个页面内容如下:
<html>
<head>
<title>fixed 水平居中 demo</title>
<style>
.fixed{
position: fixed;
width: 100px;
height: 100px;
/* top 坐标居中 */
top: 50%;
/* left 坐标居中 */
left: 50%;
/* 由于元素的高度是100px 所以此处设置为-50px以达到整个元素上移自己高度的一半,达到垂直居中 */
margin-top: -50px;
/* 由于元素的高度是100px 所以此处设置为-50px以达到整个元素左移自己宽度的一半,达到水平居中 */
margin-left: -50px;
border: solid 1px #c5c5c5;
border-radius: 5px;
background-color: blueviolet;
}
</style>
</head>
<body>
<div class="fixed"></div>
</body>
</html>
4、最终显示效果
