position:fixed 居中

2025-11-08 12:35:01

1、新建一个html文件。如图:

position:fixed 居中

2、在html文件上找<body>标签,在<body>标签里面输入一个div标签,然后给这个div标签设置一个class类为fixed,为了看得更清晰在这个div标签中输入一些内容;

<div class="fixed">

     fixed浮动居中

</div>

position:fixed 居中

3、创建div并设置基本属性。html文件找到<title>标签,在这个标签后新建一个<style>标签,然后在<style>标签里设置class类为fixed的属性为:宽为300像素,高为150像素,背景为红色,相对于浏览器窗口定位,距离浏览器顶部位置为20%

样式代码:

<style>

.fixed{

width: 300px;

height: 150px;

background-color: red;

position: fixed;

top: 20%;

}

</style>

position:fixed 居中

4、保存html文件后使用浏览器查看设置的效果。如图:

position:fixed 居中

5、设置position:fixed 居中。为了给div自动居中显示,只需要在fixed类中再添加:

left: 0;

right: 0;

margin:0 auto;

如图:

position:fixed 居中

6、查看居中效果。保存html文件后使用浏览器打开,发现position:fixed 自动居中了,不管怎么缩小放大浏览器div都是居中于浏览器的。如图:

position:fixed 居中

7、如有不明白可以把所有代码复制到新建的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 class="fixed">

fixed浮动居中

</div>

</body>

</html>

position:fixed 居中

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢