html - 将最大宽度应用于相对定位的 Div 中的固定位置的 Div?

标签 html css css-position positioning

在保持继承的 max-width 的同时,将相对 div 中的固定 div 右对齐的最佳方法是什么?

更新(2018 年 1 月 24 日):我已经用解决方案回答了这个问题。参见 here .

请参阅以下代码片段以获取更多引用:

body {
  margin: 0;
  padding: 0;
  border: 0;
}

.container {
  width: 100%;
}

.max-width {
  margin: 0 auto;
  max-width: 500px;
  height: 1000px;
  position: relative;
  box-sizing: border-box;
  background-color: lightgrey;
}

.box {
  max-width: inherit;
  width: 20%;
  height: 20px;
  position: fixed;
  background: blue;
  float: right;
  color: white;
  text-align: center;
  right: 0;
}
<div class="container">
  <div class="max-width">
    <div class="box">fix to right?</div>
  </div>
</div>

最佳答案

固定元素的位置总是相对于视口(viewport)/窗口,而不是任何其他元素。

你唯一能做的(使用 CSS)是使用 right: calc(50% - 250px); 来让它的位置右对齐到 500px 宽居中的右边界“父”元素,但这仅在屏幕宽度或等于“父”元素的 max-width 时才有效。

评论后添加:另外为宽度低于 500px 的屏幕添加一个媒体查询,right: 0(感谢@MrLister)

body {
  margin: 0;
  padding: 0;
  border: 0;
}

.container {
  width: 100%;
}

.max-width {
  margin: 0 auto;
  max-width: 500px;
  height: 1000px;
  position: relative;
  box-sizing: border-box;
  background-color: lightgrey;
}

.box {
  max-width: inherit;
  width: 20%;
  height: 20px;
  position: fixed;
  top: 0;
  right: calc(50% - 250px);
  background: blue;
  float: right;
  color: white;
  text-align: center;
}

@media (max-width: 500px) {
  .box {
    right: 0px;
  }
}
<div class="container">
  <div class="max-width">
    <div class="box">fix to right?</div>
  </div>
</div>

关于html - 将最大宽度应用于相对定位的 Div 中的固定位置的 Div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48430569/

相关文章:

javascript - 父级可调整大小时,如何防止嵌套DIV的内容溢出父级?

html - 在绝对位置和自动尺寸上保持纵横比 css

javascript - 如何在 Canvas 上的图像上执行 "paint"?

css - 试图理解一些 HTML5 样板元素

jquery - 使用 For 循环为多个元素 id 创建函数

python - 如何使用python和selenium IDE获取网页上的所有链接

javascript - 文本字段的虚拟键盘弹出onfocus

javascript - 如何展开或关闭 html/JS 中的内容 - 总是分配给不同的 id

html - 保持图像居中,同时保持 100% 高度并且只扩展/裁剪边

css - IE6中位置绝对div高度属性的Bug