按钮相对于浏览器窗口固定就是不会随着滚动条的滚动而滚动,可以选择position来实现,下面看看position的属性有哪些?
值 | 描述 |
---|---|
absolute | 生成绝对定位的元素,相对于 static 定位以外的第一个父元素进行定位。 元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。 |
fixed | 生成绝对定位的元素,相对于浏览器窗口进行定位。 元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。 |
relative | 生成相对定位的元素,相对于其正常位置进行定位。 因此,"left:20" 会向元素的 LEFT 位置添加 20 像素。 |
static | 默认值。没有定位,元素出现在正常的流中(忽略 top, bottom, left, right 或者 z-index 声明)。 |
inherit | 规定应该从父元素继承 position 属性的值。 |
因此我们选择position:fixed
代码实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
background-color: antiquewhite;
height: 1300px;
}
.btn{
width: 150px;
height: 50px;
line-height: 50px;
font-size: 22px;
position: fixed;
top: 100px;
right: 200px;
}
</style>
</head>
<body>
<div class="box"></div>
<button class="btn">固定按钮</button>
</body>
</html>