如何将 div 绝对定位在主要位置之外?
How to absolutely position a div right outside the main one?
假设我有这样的代码:
.a {
width: 400px;
height: 150px;
border: 1px solid #777;
position: relative;
}
.b {
position: absolute;
top: 30%;
right: -33px;
}
.c {
position: absolute;
top: 50%;
right: -88px;
}
<div class="a">
<div class="b">hello</div>
<div class="c">testing longer</div>
</div>
如果您 运行 代码段,您将看到所需的行为,其中 b
和 c
都位于 a
元素的右边缘。
我遇到的唯一问题是我的网站 b
和 c
有动态内容(我不知道它们会提前显示什么)。是否有可能以某种方式修改 b
和 c
的 right
属性 这样我就不必硬编码其中的值并且它们仍将位于a
?
的外边缘
您可以使用:
left: 100%
或
right: 0
和 transform: translateX(100%)
示例:
.a {
width: 400px;
height: 150px;
border: 1px solid #777;
position: relative;
}
.b, .c {
position: absolute;
right: 0;
transform: translateX(100%);
}
.b {
top: 30%;
}
.c {
top: 50%;
}
<div class="a">
<div class="b">hello</div>
<div class="c">testing longer</div>
</div>
我可能会更进一步,用另一个元素包装 .b
和 .c
,这样您也可以摆脱硬编码 top
。
.a {
width: 400px;
height: 150px;
border: 1px solid #777;
position: relative;
}
.d {
position: absolute;
top: 50%;
right: 0;
transform: translate(100%, -50%);
}
.c {
margin-top: 1em;
}
<div class="a">
<div class="d">
<div class="b">hello</div>
<div class="c">testing longer</div>
</div>
</div>
假设我有这样的代码:
.a {
width: 400px;
height: 150px;
border: 1px solid #777;
position: relative;
}
.b {
position: absolute;
top: 30%;
right: -33px;
}
.c {
position: absolute;
top: 50%;
right: -88px;
}
<div class="a">
<div class="b">hello</div>
<div class="c">testing longer</div>
</div>
如果您 运行 代码段,您将看到所需的行为,其中 b
和 c
都位于 a
元素的右边缘。
我遇到的唯一问题是我的网站 b
和 c
有动态内容(我不知道它们会提前显示什么)。是否有可能以某种方式修改 b
和 c
的 right
属性 这样我就不必硬编码其中的值并且它们仍将位于a
?
您可以使用:
left: 100%
或right: 0
和transform: translateX(100%)
示例:
.a {
width: 400px;
height: 150px;
border: 1px solid #777;
position: relative;
}
.b, .c {
position: absolute;
right: 0;
transform: translateX(100%);
}
.b {
top: 30%;
}
.c {
top: 50%;
}
<div class="a">
<div class="b">hello</div>
<div class="c">testing longer</div>
</div>
我可能会更进一步,用另一个元素包装 .b
和 .c
,这样您也可以摆脱硬编码 top
。
.a {
width: 400px;
height: 150px;
border: 1px solid #777;
position: relative;
}
.d {
position: absolute;
top: 50%;
right: 0;
transform: translate(100%, -50%);
}
.c {
margin-top: 1em;
}
<div class="a">
<div class="d">
<div class="b">hello</div>
<div class="c">testing longer</div>
</div>
</div>