top

Baseline Widely available *

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

* Some parts of this feature may have varying levels of support.

topCSS 属性定义了定位元素的上外边距边界与其包含块上边界之间的偏移,非定位元素设置此属性无效。

尝试一下

top的效果取决于元素的position属性:

  • position设置为absolutefixed时,top属性指定了定位元素上外边距边界与其包含块上边界之间的偏移。
  • position设置为relative时,top属性指定了元素的上边界离开其正常位置的偏移。
  • position设置为sticky时,如果元素在 viewport 里面,top属性的效果和 position 为relative等同;如果元素在 viewport 外面,top属性的效果和 position 为fixed等同。
  • position设置为static时,top属性无效。

topbottom同时指定时,并且 height没有被指定或者指定为auto的时候,topbottom 都会生效,在其他情况下,如果 height被限制,则top属性会优先设置,bottom属性则会被忽略。

初始值auto
适用元素positioned elements
是否是继承属性
Percentagesrefer to the height of the containing block
计算值if specified as a length, the corresponding absolute length; if specified as a percentage, the specified value; otherwise, auto
动画类型a length, percentage or calc();

语法

css
/* <length> 值 */
top: 3px;
top: 2.4em;
top: anchor(bottom);
top: calc(anchor(--myAnchor 50%) + 10px);

/* 相对于包含区块高度的 <percentage> */
top: 10%;

/* 关键字值 */
top: auto;

/* 全局值 */
top: inherit;
top: initial;
top: revert;
top: revert-layer;
top: unset;

取值

<length>

可以是负的、null 或正的 <length> 值,用于表示:

  • 对于绝对定位的元素,元素下外边距边界与其包含块下边界之间的偏移。
  • 对于相对定位定位的元素,元素的下边界离开其正常位置的偏移。
<percentage>

代表元素包含块的高度的百分比 <percentage>

auto

表示:

  • 对于绝对定位元素,元素的定位基于 bottom 属性,height: auto 被视为基于内容的高度;或者,如果 bottom 也是 auto,则元素将按其作为静态元素时应垂直定位的位置进行定位。
  • 对于相对定位元素,元素相对于其正常位置的偏移量基于 bottom 属性;如果 bottom 也是 auto,则元素将不会在垂直方向上移动。
inherit

表示该值与其父元素(可能不是它的包含块)的计算值相同。对这个计算值的处理将和它原本为 <length><percentage>auto 关键字一样。

示例

css
body {
  background: beige;
}

div {
  position: absolute;
  top: 10%;
  right: 40%;
  bottom: 20%;
  left: 15%;
  background: gold;
  border: 1px solid blue;
}
html
<div>The size of this content is determined by the position of its edges.</div>

规范

Specification
CSS Positioned Layout Module Level 3
# insets

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
top
anchor()
Experimental
anchor-size()
Experimental
auto

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
In development. Supported in a pre-release version.
In development. Supported in a pre-release version.
No support
No support
Experimental. Expect behavior to change in the future.
See implementation notes.