此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
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 属性定义了定位元素的上外边距边界与其包含块上边界之间的偏移,非定位元素设置此属性无效。
In this article
尝试一下
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设置为absolute或fixed时,top属性指定了定位元素上外边距边界与其包含块上边界之间的偏移。 - 当
position设置为relative时,top属性指定了元素的上边界离开其正常位置的偏移。 - 当
position设置为sticky时,如果元素在 viewport 里面,top属性的效果和 position 为relative等同;如果元素在 viewport 外面,top属性的效果和 position 为fixed等同。 - 当
position设置为static时,top属性无效。
当top和bottom同时指定时,并且height没有被指定或者指定为auto的时候,top和bottom 都会生效,在其他情况下,如果height被限制,则top属性会优先设置,bottom属性则会被忽略。
语法
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表示:
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> |