方法/步骤
-
新建一个html文件。如图:
-
在html文件上找<body>标签,在<body>标签中创建<div>标签并设置class类:
<div class="fixed">
fixed浮动居中
</div>
如图:
-
对div设置基本属性。html文件找到<title>标签,在这个标签后新建一个<style>标签,然后在<style>标签里设置class类为fixed的属性为:宽为300像素,高为150像素,背景为红色,相对于浏览器窗口定位,距离浏览器顶部位置为20%
样式代码:
<style>
.fixed{
width: 300px;
height: 150px;
background-color: red;
position: fixed;
top: 20%;
}
</style>
-
查看样式效果,保存html文件后使用浏览器查看设置的效果。如图:
-
设置position:fixed 居中。为了给div自动居中显示,只需要在fixed类中再添加:
left: 0;
right: 0;
margin:0 auto;
如图:
-
查看居中效果。保存html文件后使用浏览器打开,浮动就居中了。如图:
-
把所有代码复制到新建的html文件保存后使用浏览器打开即可看到效果。
所有代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>position: fixedn居中</title>
<style>
.fixed{
width: 300px;
height: 150px;
background-color: red;
position: fixed;
top: 20%;
left: 0;
right: 0;
margin:0 auto;
}
</style>
</head>
<body>
<div>
fixed浮动居中
</div>
</body>
</html>
-