一、了解 position
属性
CSS 的 position
属性允许你控制元素的定位。它有五个值:static
、relative
、absolute
、fixed
和 sticky
。以下是每个值的简要说明:
static
:默认值,元素根据正常文档流定位。relative
:相对于其正常位置进行定位。absolute
:相对于最近的已定位祖先元素进行定位,脱离文档流。fixed
:相对于视口进行定位,脱离文档流。sticky
:结合了relative
和fixed
的特性,元素在达到指定位置后固定。
二、图片水平居中
.container {
display: flex;
justify-content: center;
}
.image {
max-width: 100%;
}
HTML 结构:
<div class="container">
<img class="image" src="image.jpg" alt="描述">
</div>
三、图片垂直居中
.container {
display: flex;
justify-content: center;
align-items: center;
height: 300px; /* 高度根据需要设置 */
}
.image {
max-width: 100%;
}
HTML 结构与上例相同。
四、图片固定位置
.image {
position: fixed;
top: 50px;
left: 50px;
width: 200px;
}
五、图片随滚动固定
.image {
position: sticky;
top: 0;
width: 150px;
}