topCSS 属性定义了定位元素的上外边距边界与其包含块上边界之间的偏移,非定位元素设置此属性无效。
{{InteractiveExample("CSS Demo: top")}}
```css interactive-example-choice top: 0;
```css interactive-example-choice
top: 4em;
```css interactive-example-choice top: 10%;
```css interactive-example-choice
top: 20px;
```html interactive-example
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.
```css interactive-example
.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和{{cssxref("bottom")}}同时指定时,并且 {{cssxref("height")}}没有被指定或者指定为auto的时候,top和{{cssxref("bottom")}} 都会生效,在其他情况下,如果 {{cssxref("height")}}被限制,则{{cssxref("top")}}属性会优先设置,bottom属性则会被忽略。
{{cssinfo}}
语法
/* <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;
取值
{{cssxref("<length>")}}
- : 可以是负的、null 或正的 {{cssxref("<length>")}} 值,用于表示:
- 对于绝对定位的元素,元素下外边距边界与其包含块下边界之间的偏移。
- 对于相对定位定位的元素,元素的下边界离开其正常位置的偏移。
{{cssxref("<percentage>")}}
- : 代表元素包含块的高度的百分比 {{cssxref("<percentage>")}}。
auto- : 表示:
- 对于绝对定位元素,元素的定位基于 {{Cssxref("bottom")}} 属性,
height: auto被视为基于内容的高度;或者,如果bottom也是auto,则元素将按其作为静态元素时应垂直定位的位置进行定位。 - 对于相对定位元素,元素相对于其正常位置的偏移量基于 {{Cssxref("bottom")}} 属性;如果
bottom也是auto,则元素将不会在垂直方向上移动。
inherit- : 表示该值与其父元素(可能不是它的包含块)的计算值相同。对这个计算值的处理将和它原本为 {{cssxref("<length>")}}、{{cssxref("<percentage>")}} 或
auto关键字一样。
- : 表示该值与其父元素(可能不是它的包含块)的计算值相同。对这个计算值的处理将和它原本为 {{cssxref("<length>")}}、{{cssxref("<percentage>")}} 或
示例
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('示例','100%','200')}}