--- title: top slug: Web/CSS/top translation_of: Web/CSS/top ---
top样式属性定义了定位元素的上外边距边界与其包含块上边界之间的偏移,非定位元素设置此属性无效。
/* <length> values */
top: 3px;
top: 2.4em;
/* 参照于包含块高度的百分比 */
top: 10%;
/* Keyword value */
top: auto;
/* Global values */
top: inherit;
top: initial;
top: unset;
top的效果取决于元素的position属性:
position设置为absolute或fixed时,top属性指定了定位元素上外边距边界与其包含块上边界之间的偏移。position设置为relative时,top属性指定了元素的上边界离开其正常位置的偏移。position设置为sticky时,如果元素在viewport里面,top属性的效果和position为relative等同;如果元素在viewport外面,top属性的效果和position为fixed等同。position设置为static时,top属性无效。当top和{{cssxref("bottom")}}同时指定时,并且 {{cssxref("height")}}没有被指定或者指定为auto的时候,top和{{cssxref("bottom")}}都会生效,在其他情况下,如果 {{cssxref("height")}}被限制,则{{cssxref("top")}}属性会优先设置,bottom属性则会被忽略。
{{cssinfo}}
autoheight: auto,将基于内容需要的高度设置高度;如果bottom也为auto的话,元素的垂直位置就是它假如作为静态(即static)元素时该在的位置。bottom也为auto的话,元素将不会有偏移。inheritauto 一样。body {
background: beige;
}
div {
position: absolute;
top: 10%;
right: 40%;
bottom: 20%;
left: 15%;
background: gold;
border: 1px solid blue;
}
<div>The size of this content is determined by the position of its edges.</div>
{{EmbedLiveSample('Example','100%','200')}}
| Specification | Status | Comment |
|---|---|---|
| {{SpecName('CSS3 Transitions', '#animatable-css', 'top')}} | {{Spec2('CSS3 Transitions')}} | Defines top as animatable. |
| {{SpecName('CSS3 Positioning', '#propdef-top', 'top')}} | {{Spec2('CSS3 Positioning')}} | Adds behavior for sticky positioning. |
| {{SpecName('CSS2.1', 'visuren.html#propdef-top', 'top')}} | {{Spec2('CSS2.1')}} | Initial definition. |
{{Compat("css.properties.top")}}