在保持继承的 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/