CSS: 将元素绝对定位到绝对父级
CSS: position element absolutely to absolute parent
我的页面侧面有一个固定的导航栏。我想在导航栏的底部有一个菜单,在里面有一个按钮,在右侧有一个锚标签形式的按钮。所以我用 bottom: 0
对菜单使用绝对定位。这工作得很好。但是当我想绝对定位按钮时,菜单的高度设置为 0,按钮似乎在整个导航栏下方。
HTML 和 CSS:
.fixed {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 100%;
width: 200px;
border:solid;
}
.menu {
position: absolute;
left: 0;
right: 0;
bottom: 0;
border: solid;
}
.btn {
position: absolute;
right: 0;
border: solid;
}
<div class="fixed">
<div class="menu">
<a class="btn">
Hello
</a>
</div>
</div>
float: right
也没有用,通过这种方法按钮仍然在左侧。如何将按钮放置在菜单的右侧?
为什么不直接使用 text-align:right
?
.fixed {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 100%;
width: 200px;
border:solid;
}
.menu {
position: absolute;
left: 0;
right: 0;
bottom: 0;
border: solid;
text-align:right;
}
<div class="fixed">
<div class="menu">
<a class="btn">
Hello
</a>
</div>
</div>
我看不出为什么您的按钮显示在左侧 float:right
,也许涉及其他规则?
此外,由于浮动元素脱离了流程,如果您希望 .menu
调整高度以适应 link,您应该应用 clearfix:
.fixed {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 100%;
width: 200px;
border: 1px solid red;
}
.menu {
position: absolute;
left: 0;
right: 0;
bottom: 0;
border: 1px solid blue;
}
.btn {
float: right;
border: 1px solid green;
}
.clearfix::after {
content: "";
clear: both;
display: table;
}
<div class="fixed">
<div class="menu">
<a class="btn">
Hello
</a>
<div class="clearfix"></div>
</div>
</div>
我的页面侧面有一个固定的导航栏。我想在导航栏的底部有一个菜单,在里面有一个按钮,在右侧有一个锚标签形式的按钮。所以我用 bottom: 0
对菜单使用绝对定位。这工作得很好。但是当我想绝对定位按钮时,菜单的高度设置为 0,按钮似乎在整个导航栏下方。
HTML 和 CSS:
.fixed {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 100%;
width: 200px;
border:solid;
}
.menu {
position: absolute;
left: 0;
right: 0;
bottom: 0;
border: solid;
}
.btn {
position: absolute;
right: 0;
border: solid;
}
<div class="fixed">
<div class="menu">
<a class="btn">
Hello
</a>
</div>
</div>
float: right
也没有用,通过这种方法按钮仍然在左侧。如何将按钮放置在菜单的右侧?
为什么不直接使用 text-align:right
?
.fixed {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 100%;
width: 200px;
border:solid;
}
.menu {
position: absolute;
left: 0;
right: 0;
bottom: 0;
border: solid;
text-align:right;
}
<div class="fixed">
<div class="menu">
<a class="btn">
Hello
</a>
</div>
</div>
我看不出为什么您的按钮显示在左侧 float:right
,也许涉及其他规则?
此外,由于浮动元素脱离了流程,如果您希望 .menu
调整高度以适应 link,您应该应用 clearfix:
.fixed {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 100%;
width: 200px;
border: 1px solid red;
}
.menu {
position: absolute;
left: 0;
right: 0;
bottom: 0;
border: 1px solid blue;
}
.btn {
float: right;
border: 1px solid green;
}
.clearfix::after {
content: "";
clear: both;
display: table;
}
<div class="fixed">
<div class="menu">
<a class="btn">
Hello
</a>
<div class="clearfix"></div>
</div>
</div>