CSS positioning (relative positioning, fixed positioning, absolute positioning)

In CSS, you can use the position attribute to position elements. The position attribute specifies the positioning type of the element.

Property value:

  • absolute : Generate absolutely positioned elements, which are positioned relative to the first parent element other than static positioning. The position of the element is specified by the "left", "top", "right" and "bottom" attributes.

  • fixed : Generate fixed positioning elements and position them relative to the browser window. The position of the element is specified by the "left", "top", "right" and "bottom" attributes.

  • relative : Generate relatively positioned elements and position them relative to their normal positions. Therefore, "left:20" will add 20 pixels to the LEFT position of the element.

  • static : The default value. Without positioning, the element appears in the normal flow (ignoring top, bottom, left, right or z-index declarations).

Relative positioning:

Positioning relative to its normal position. (Can be used to fine-tune the position of the label)

 <html>
<head>
<title>相对定位</title>
<meta charset="utf-8">
<style type="text/css">
body{
height: 2000px;
}
#span2{
position: relative;/*设置定位方式为相对定位*/
top: 20px;
left: 14px;
}
</style>
</head>
<body>
<span id="span1">这是一</span>
<span id="span2">这是二</span>
<span id="span3">这是三</span>
</body>
</html>

Fixed positioning

Always position relative to the browser window.

<html>
<head>
<title>固定定位</title>
<meta charset="utf-8">
<style type="text/css">
body{
height: 2000px;
}
div{
width: 500px;
height: 300px;
border:solid 2px red;
position: fixed;/*设置定位方式为固定定位*/
bottom:500px 1px ;
}
p{
float: right;
}
</style>
</head>
<body>
<div>这是一个div盒子</div><br>
<p>这个不会动</p>
</body>
</html>

Absolute positioning

Positioning relative to the first parent element other than static positioning.

<head>
<title>绝对定位</title>
<meta charset="utf-8">
<style type="text/css">
div{
width: 500px;
height: 400px;
border: solid 2px red;
/*给div设置相对定位,使得div作为section的参照物进行绝对定位*/
position: relative;
}
section{
width: 50px;
height: 40px;
background-color: yellow;
position: absolute;/*设置定位方式为绝对定位*/
/*让section始终在div右下角*/
/*让section相对在div右侧距离为0*/
/*让section相对在div低侧距离为0*/
/*绝对定位必须设置参照物,若未设置参照物,则相对于body进行定位*/
right: 0px;
bottom: 0px;
}

</style>
</head>
<body>
<div>
<section></section>
</div>
</body>

Guess you like

Origin blog.csdn.net/QIANDXX/article/details/113185358
Recommended