我可以完全根据它自己的底边定位一个元素吗?

时间:2015-03-26 02:31:29

标签: css css-position absolute

我需要定位一个元素,使其只是离开屏幕顶部(这将是一个向下滑动的菜单)。当然,我可以使用position: absolutetop: 0px,但这将基于我的元素 top 边缘按元素定位。

我可以使用我的元素 bottom 边缘吗?

示例:

#foo {
  position: absolute;
  top: 0px;
  }

会给我这个:

-------------------------------------------
|              |                          | 
|   id="foo"   |        <body>            | 
----------------                          | 
|                                         | 
|                                         | 
-------------------------------------------

但有没有办法通过CSS获得这个:

----------------
|              |      
|   id="foo"   |  
-------------------------------------------
|                                         | 
|                       <body>            | 
|                                         | 
|                                         | 
|                                         | 
-------------------------------------------

我想要完成的是使用div的 bottom 边缘而不是顶部将具有未知高度的div(因为内容可变)放置到文档的最顶部。

或者这不是CSS本身可以处理的东西吗?

2 个答案:

答案 0 :(得分:4)

您似乎希望从100%

中定位元素bottom

Example Here

#foo {
    position: absolute;
    bottom: 100%;
}

.parent {
    width: 400px;
    height: 200px;
    margin: 75px;
    position: relative;
    border: 1px solid;
}
.child {
    width: 200px;
    height: 50px;
    background: red;
    position: absolute;
    bottom: 100%;
}
<div class="parent">
    <div class="child"></div>
</div>

答案 1 :(得分:4)

一种方法是使用translateY(-100%)

&#13;
&#13;
div {
  transform: translateY(-100%);
  background: red;
}
body {
    margin:0;
}
&#13;
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed lacinia porta lacus ac egestas. Nam et elit lacus. Aliquam elementum felis imperdiet arcu commodo sollicitudin. Maecenas quis lectus in risus semper venenatis. Vestibulum eu bibendum diam. Cras
  aliquam elit sit amet dui vehicula, sit amet dignissim nulla convallis. Integer finibus, nisl maximus accumsan congue, ligula eros efficitur magna, ac gravida sapien dolor at leo. Morbi tempus ex lacus. Maecenas fermentum ut nisl at tincidunt. Etiam
  aliquet a ex vitae posuere. Nam ultrices tortor a congue ullamcorper. Quisque sit amet cursus magna, a finibus mauris. Duis at placerat orci, vitae ultrices dolor. Cras posuere, arcu ut ornare pharetra, neque justo aliquam orci, sodales viverra mi massa
  a quam. Morbi sollicitudin justo sapien, congue feugiat arcu vehicula et. Integer faucibus leo sit amet enim efficitur, ac laoreet lectus eleifend. Donec sit amet risus massa. Ut et nunc augue. Cras efficitur tellus sapien, nec viverra leo semper sed.
  Vivamus ut sollicitudin metus. Nulla et bibendum sapien, vel consequat lorem. Phasellus mi diam, fringilla sed iaculis in, aliquam non lorem. Integer ac vestibulum massa, sed aliquet dui. Nulla facilisi. Suspendisse congue tortor ut vestibulum dignissim.
  Vestibulum quis est id est consectetur ultricies. Aliquam vitae suscipit purus.
</div>
&#13;
&#13;
&#13;