当元素处于绝对位置或固定位置(即 position: absolute; 和 position: fixed ;)时, top 属性指定元素的顶部边缘与其包含块(元素相对放置的祖先)之间的距离。
如果元素相对定位(即 position: relative ;),则top属性会将元素的顶部边缘从其正常位置移到上方/下方。
如果position设置为sticky(即position: sticky;;),则定位上下文是视口。当元素在视口中时, top 属性的行为就像其位置是相对的。当元素位于外部时, top 属性的行为就像其位置是固定的。
top: auto | length | percentage | initial | inherit;
<!DOCTYPE html>
<html>
<head>
<title>
CSS top Property
</title>
<style>
div{
position: relative;
width: 150px;
height: 150px;
font-size: 30px;
}
#len {
top: -75px;
border: 5px solid green;
}
#em {
top: -2em;
border: 5px solid blue;
}
#auto {
top: auto;
border: 5px solid red;
}
#init {
top: initial;
border: 5px solid darkviolet;
}
h1{
text-align: center;
}
</style>
</head>
<body>
<h1> Example of the top Property </h1>
<div id = "len"> top: -75px; </div>
<div id = "em"> top: -2em; </div>
<div id = "auto"> top: auto; </div>
<div id = "init"> top: initial; </div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>
CSS top Property
</title>
<style>
div{
position: absolute;
width: 150px;
height: 150px;
font-size: 30px;
}
#len {
top: 250px;
border: 5px solid lightgreen;
}
#per {
top: 60%;
border: 5px solid blue;
}
#auto {
top: auto;
border: 7px solid red;
}
#init {
top: initial;
border: 5px solid lightblue;
}
</style>
</head>
<body>
<h1> Example of the top Property </h1>
<div id = "len"> top: 250px; </div>
<div id = "per"> top: 60%; </div>
<div id = "auto"> top: auto; </div>
<div id = "init"> top: initial; </div>
</body>
</html>