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.
top
CSS 属性定义了定位元素的上外边距边界与其包含块上边界之间的偏移,非定位元素设置此属性无效。
尝试一下
top: 0;
top: 4em;
top: 10%;
top: 20px;
I am absolutely positioned.
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.
.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
/* 值 */
top: 3px;
top: 2.4em;
top: anchor(bottom);
top: calc(anchor(--myAnchor 50%) + 10px);
/* 相对于包含区块高度的 */
top: 10%;
/* 关键字值 */
top: auto;
/* 全局值 */
top: inherit;
top: initial;
top: revert;
top: revert-layer;
top: unset;
取值
示例
css
body {
background: beige;
}
div {
position: absolute;
top: 10%;
right: 40%;
bottom: 20%;
left: 15%;
background: gold;
border: 1px solid blue;
}
html
The size of this content is determined by the position of its edges.
规范
Specification |
---|
CSS Positioned Layout Module Level 3 # insets |