html - 两个子 div,一个相对父 div 的位置,另一个相对浏览器?

标签 html css

这是我的html
a.html

<div class='main'>
  <div class="sub1"></div>
  <div class="sub2"></div>
</div>

和CSS:
a.css

.main {
  width: 200px;
  height: 400px;
  margin-left: 100px;
  position: relative;
  border: 1px solid red;
}

.sub1 {
  width: 100px;
  height: 100px;
  border: 1px solid;
  position: absolute;
  left: 0px;
}

.sub2 {
  width: 50px;
  height: 300px;
  position: absolute;
  top: 30px;
  left: 20px;
  border: 1px solid green;
}  

现在我要div.sub1是相对于父div的,
div.sub2是相对于浏览器的,
如何将样式设置为 div.sub2

最佳答案

据我所知,有两种可能的解决方案,要么将第二个 div 放在父 div 之外。这样 .sub2 就不会是父 div 的子元素了。

或者使第二个 div position:fixed 而不是绝对的。

.sub2 {
  width: 50px;
  height: 300px;
  position: fixed;
  top: 30px;
  left: 20px;
  border: 1px solid green;
} 

Fiddle

关于html - 两个子 div,一个相对父 div 的位置,另一个相对浏览器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34627142/

相关文章:

javascript - 有没有办法检测溢出 y :auto has been triggered, 并因此创建弹出窗口?

php - 如何在提交表单时验证 Google reCaptcha

html - 在 css 中使用 text-fill-color 来剪切文本真的有必要吗?

Javascript 叠加函数

javascript - 值被连接而不是相加

PHP 包含函数和 AJAX div 加载

javascript - 只想在我的选项卡中使用 css 而不是 js 和查询

php - 用 “CSS” 创建 “PHP”

html - Bootstrap Mobile Menu子菜单克拉不可见

jquery - 灯箱的 CSS