如何创建一个固定的 div?

10

我想让一个框固定在页面的右下角,不随页面的滚动而移动。但是我的代码并没有奏效,不知道为什么。这是我的代码:

<html>
 <head>

 <style type="text/css">

.tooltip {
 width: 200px;
 position: fixed;
 top:auto;
 bottom:0px;
 right:0px;
 left:auto;
}
 </style>
 </head> 
<body>
<div class="tooltip">
   <div class="tooltip_top">1</div>
   <div class="tooltip_con">2</div>
   <div class="tooltip_bot">3</div>
 </div>
</body>
</html>

对我来说很好用。即使顶部和左侧的自动值不是必需的。问题出在哪里?你用什么浏览器进行测试? - gregseth
10个回答

12

在Firefox和Chrome中,它能够正常工作。

早期版本的IE对于position:fixed支持不正确,最新版本不确定是否支持。

还要确保定义了文档类型。


7
.tooltip {
 width: 200px;
 position: fixed;
 bottom:0px;
 right:0px;
}

2
嗯,应该可以奏效。也许需要去除“top: auto”?
(但是在IE 6中无法奏效,因为IE 6不支持“position:fixed”。)

2

对我而言似乎可以工作... 我相信在IE7及更高版本中,您需要定义一个文档类型,请搜索“怪异模式”(quirks mode)以了解如何开始。

我认为IE6不支持position:fixed。


先生,您说得对。如果您想节省一些字节,使用绝对定位是有效的。 - Nick Larsen

1
<html>
 <head>
 <style type="text/css">
.header {
 width: 100%;
 height:100px;
 position: fixed;
 top:0px;
 left:0px;
}
 </style>
 </head> 
<body>
<div class="tooltip">
   <div class="tooltip_top">1</div>
   <div class="tooltip_con">2</div>
   <div class="tooltip_bot">3</div>
 </div>
</body>
</html>

1

如果有任何与职位相关的问题,请查看此链接,您将获得快速解决方案。

http://learnlayout.com/position.html

固定

固定元素相对于视口定位,这意味着即使页面滚动,它仍然保持在相同的位置。与相对定位类似,使用top、right、bottom和left属性。

我相信你已经注意到了页面右下角的固定元素。现在我允许你关注它。以下是将其放置在那里的CSS:

.fixed {
  position: fixed;
  bottom: 0;
  right: 0;
  width: 200px;
  background-color: white;
}

相对定位

相对定位与静态定位相同,除非您添加一些额外的属性。

.relative1 {
  position: relative;
}
.relative2 {
  position: relative;
  top: -20px;
  left: 20px;
  background-color: white;
  width: 500px;
}

绝对定位(absolute)

绝对定位是最棘手的定位方式。它的行为与固定定位类似,但是相对于最近的已定位祖先元素而不是相对于视口进行定位。如果一个绝对定位的元素没有任何已定位的祖先元素,那么它将使用文档主体,并且随着页面滚动而移动。请记住,"已定位"的元素是指其位置不是静态的元素。

以下是一个简单的示例:

.relative {
  position: relative;
  width: 600px;
  height: 400px;
}
.absolute {
  position: absolute;
  top: 120px;
  right: 0;
  width: 300px;
  height: 200px;
}

1

你的HTML/CSS在IE浏览器中出现了问题。将 position: fixed; 改为 position: absolute;,它应该会更符合你的要求。

你也可以应用文档类型元素:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

1

所有答案都有“大代码” 为什么不在div元素中添加“fixed”呢? 像这样:

div position: fixed;

就是这样:D 希望它对你有用


1

是的,有两件事要注意

  • 写DOCTYPE,但是过渡的!
  • "position:fixed"的CSS属性不受IE6支持...所以最好使用"position:absolute"...其他属性保持不变。

1
像这样的东西应该可以工作。
<style>
    #myheader{
        position: fixed;
        left: 0px;
        top: 95vh;
        height: 5vh;
    }
</style>
<body>
    <div class="header" id = "myheader">
</body>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接