top
        
        Baseline  广泛可用  *
        
        
          
                
              
                
              
                
              
        
        
      
      
    试一试
top: 0;
top: 4em;
top: 10%;
top: 20px;
<section id="default-example">
  <div class="example-container">
    <div id="example-element">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属性指定元素顶部外边距边缘与其包含块顶部内边框边缘之间的距离,或者,在锚点定位元素中使用anchor()函数时,相对于指定的<anchor-side>边缘。top属性与top、bottom、start、end、self-start、self-end、center和<percentage>值兼容。
- 当 position设置为relative时,top属性指定元素的顶部边缘在其正常位置下方移动的距离。
- 当 position设置为sticky时,top属性用于计算粘性约束矩形。
- 当 position设置为static时,top属性无效。
当同时指定 top 和 bottom 值时,有三种不同情况
- 如果 position设置为absolute或fixed且height未指定(auto或100%),则top和bottom值都会被尊重。
- 如果 position设置为relative或height受到限制,则top属性优先,bottom属性被忽略。
- 如果 position设置为sticky,则top和bottom值都会被考虑。这意味着粘性元素可以在其包含块内上下移动,只要元素的定位框保持在其包含块内。
语法
css
/* <length> values */
top: 3px;
top: 2.4em;
top: anchor(bottom);
top: anchor-size(--my-anchor self-block, 10%);
/* <percentage>s of the height of the containing block */
top: 10%;
/* Keyword value */
top: auto;
/* Global values */
top: inherit;
top: initial;
top: revert;
top: revert-layer;
top: unset;
值
- <length>
- 
负值、零值或正值 <length>- 对于绝对定位元素,它表示到包含块顶部边缘的距离。
- 对于锚点定位元素,anchor()函数解析为一个<length>值,相对于关联的锚点元素的顶部或底部边缘的位置(参见将内嵌属性与anchor()函数值一起使用),而anchor-size()函数解析为一个<length>值,相对于关联的锚点元素的宽度或高度(参见根据锚点大小设置元素位置)。
- 对于相对定位元素,它表示元素在其正常位置下方移动的距离。
 
- <percentage>
- 
包含块高度的 <percentage>。
- auto
- 
指定 
正式定义
正式语法
top =
auto |
<length-percentage> |
<anchor()> |
<anchor-size()>
<length-percentage> =
<length> |
<percentage>
<anchor()> =
anchor( <anchor-name>? &&
<anchor-side> , <length-percentage>? )
<anchor-size()> =
anchor-size( [ <anchor-name> || <anchor-size> ]? , <length-percentage>? )
<anchor-name> =
<dashed-ident>
<anchor-side> =
inside |
outside |
top |
left |
right |
bottom |
start |
end |
self-start |
self-end |
<percentage> |
center
<anchor-size> =
width |
height |
block |
inline |
self-block |
self-inline
示例
一个距顶部 10% 的定位元素
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>
规范
| 规范 | 
|---|
| CSS 定位布局模块第 3 级 # 内嵌 | 
浏览器兼容性
加载中…