【问题标题】:CSS: position element absolutely to absolute parentCSS:将元素绝对定位到绝对父级
【发布时间】:2018-07-09 03:14:45
【问题描述】:

我的页面一侧有一个固定的导航栏。我想在导航栏的底部有一个菜单,在里面有一个右侧的锚标签形式的按钮。所以我用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也不起作用,使用这种方法,按钮仍然在左侧。如何将按钮定位在菜单的右侧?

【问题讨论】:

  • 按钮上的margin-left:auto; 和/或菜单上的text-align:right
  • @Pete text-align:right 显然有效。谢谢你:)

标签: html css position absolute


【解决方案1】:

为什么不直接使用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>

【讨论】:

    【解决方案2】:

    我看不出您的按钮为什么会在左侧显示float:right,可能涉及其他规则?

    此外,由于浮动元素会脱离流程,如果您希望 .menu 调整链接的高度,您应该应用 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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-05
      • 2015-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-16
      相关资源
      最近更新 更多