Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. CSS:层叠样式表
  3. CSS 参考
  4. 属性
  5. top

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in EnglishAlways switch to English

top

Baseline Widely available *

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

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

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

尝试一下

top: 0;
top: 4em;
top: 10%;
top: 20px;
<section>  <div>    <div>I am absolutely positioned.</div>    <p>      As much mud in the streets as if the waters had but newly retired from the      face of the earth, and it would not be wonderful to meet a Megalosaurus,      forty feet long or so, waddling like an elephantine lizard up Holborn      Hill.    </p>  </div></section>
.example-container {  border: 0.75em solid;  padding: 0.75em;  text-align: left;  position: relative;  width: 100%;  min-height: 200px;}#example-element {  background-color: #264653;  border: 4px solid #ffb500;  color: white;  position: absolute;  width: 140px;  height: 60px;}

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
动画类型alength,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

浏览器兼容性

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp