top 属性结合 position 属性定义元素的顶部位置。
top 属性的效果取决于元素的定位方式(参见 position 属性)。
- 如果 position 设置为“absolute”或者“fixed”,则 top 属性将元素的顶部边缘指定为其最近定位的祖先顶部边缘上方/下方的单位。
- 如果 position 设置为“relative”,则 top 属性指定要在其正常位置上方/下方移动的顶部边缘。
- 如果 position 设置为“sticky”,则当元素在视口内时 top 属性将其位置更改为相对位置,当元素在视口外时更改为固定位置。
- 当 position 属性设置为“static”时,则不应用 position 属性。
允许负值。
初始值 | auto |
---|---|
应用于 | 定位元素。 |
继承 | 无效 |
可动画的 | 是的。 |
版本 | CSS2. |
DOM 语法 | object.style.top =“50px”; |
语法
top: auto | length | initial | inherit;
top 属性示例:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> <style> div { background-color: #8ebf42; height: 200px; width: 600px; position: relative; } p { margin: 0; color: #eee; position: absolute; border: 2px solid #666; } .ex1 { top: 0; } .ex2 { top: 50px; } </style> </head> <body> <h2>Top 属性示例</h2> <div> <p class="ex1">Some text (top: 0;)</p> <p class="ex2"> 生活终归还得继续。...生活本就是矛盾的,白天与黑夜间的距离,春夏秋冬之间的轮回,于是有了挑剔的喜爱,让无奈加上了喜悦的等待。 </p> </div> </body> </html>
具有负值的 top 属性示例:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> <style> div { background-color: #666; height: 200px; position: relative; } p { margin: 0; color: #fff; } .top { position: absolute; top: -35px; color: #000000; } </style> </head> <body> <h2>Top 属性示例</h2> <div> <p>Some text.</p> <p class="top">Text with the top property.</p> </div> </body> </html>
"pt"、"%" 和 "em" 中定义的 top 属性示例:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> <style> div { background-color: #8ebf42; height: 200px; width: 600px; position: relative; } p { margin: 0; color: #eee; position: absolute; border: 2px solid #666; } .ex1 { top: 5em; } .ex2 { top: 10pt; } .ex3 { top: 75%; } </style> </head> <body> <h2>Top 属性示例</h2> <div> <p class="ex1">Some text (top: 0;)</p> <p class="ex2"> 生活终归还得继续。...生活本就是矛盾的,白天与黑夜间的距离,春夏秋冬之间的轮回,于是有了挑剔的喜爱,让无奈加上了喜悦的等待。 </p> <p class="ex3"> 生活终归还得继续。...生活本就是矛盾的,白天与黑夜间的距离,春夏秋冬之间的轮回,于是有了挑剔的喜爱,让无奈加上了喜悦的等待。 </p> </div> </body> </html>
CSS top 属性值说明
值 | 描述 |
---|---|
auto | 设置顶部边缘位置。这是此属性的默认值。 |
length | 使用PX,CM等设置顶部边缘位置。负值有效。 |
% | 使用包含元素的百分比设置顶部边缘位置。负值有效。 |
initial | 使属性使用其默认值。 |
inherit | 从父母元素继承属性。 |
日期:2020-06-02 22:14:50 来源:oir作者:oir