CSS bottom 属性


CSS bottom 属性

CSS中的bottom属性定义了一个元素的底部边缘相对于其容器的底部边缘的位置。bottom属性只适用于已定位的元素(position属性值为absolute、fixed、sticky)。

语法

bottom: length | initial | inherit;
  • length:元素距离容器底部的距离,可以是带单位的数值,如10px或者百分比,如50%
  • initial:此值表示bottom属性被设置为它的默认值,即0。
  • inherit:继承bottom属性值。

示例

<style>
  .container {
    position: relative;
    height: 300px;
    width: 500px;
    background-color: #f1f1f1;
  }
  .box {
    position: absolute;
    bottom: 20px;
    right: 20px;
    width: 100px;
    height: 100px;
    background-color: #333;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>

<div class="container">
  <div class="box">
    Bottom
  </div>
</div>

bottom属性示例

如上代码所示,.box元素通过设置bottom:20px使其距离父容器的底部边缘为20px。

注意事项

  • bottom值(包括百分比值)定义了一个元素相对于其容器底部边界的偏移量。如果指定了bottom值,则该元素将从底部向上方移动
  • 如果bottom和top同时指定了一个值,则bottom值将优先于top值
  • 请不要使用负数值作为bottom属性值,这可能导致元素越出容器并被裁剪
  • 如果一个元素未被定位(position值为static),那么bottom属性无效
  • 如果设置了2个相反的位置属性(比如bottom和top、left和right),则只有一个有效。

总结

bottom属性定义了一个元素相对于其容器底部边缘的位置。 通过设置bottom属性,我们可以控制元素的位置,并实现各种布局效果。 但需要注意的是,bottom属性只适用于已定位的元素,且当元素设置两个相反的位置属性时,只有一个位置属性是有效的。