在 web 开发中,top
属性用于设置元素相对于其包含块顶部的偏移量。这个属性通常与 position
属性一起使用,用来控制元素的定位。
语法
selector { top: length|percentage|auto|initial|inherit; }
length
:指定一个固定的长度值,比如10px
或2rem
。percentage
:指定一个相对于包含块高度的百分比值,比如50%
。auto
:默认值,元素的位置由文档流确定。initial
:将属性重置为默认值。inherit
:继承父元素的值。
示例
-- -------------------- ---- ------- ---------- - --------- --------- ---- ----- - ---- - --------- --------- ---- ---- -展开代码
在上面的示例中,.container
元素设置了 position: relative;
,然后根据 top: 20px;
的值,.container
内部的元素将会向下偏移 20 像素。而 .box
元素设置了 position: absolute;
,并且 top: 50%;
,这将导致 .box
元素相对于其包含块的顶部偏移了包含块高度的一半。
注意事项
- 当元素的
position
属性值为static
或relative
时,top
属性不会产生视觉上的偏移效果。 - 当元素的
position
属性值为absolute
或fixed
时,top
属性将相对于包含块的顶部进行定位。