如何垂直居中一个浮动元素?
垂直居中一个浮动元素可以使用以下两种方法:
方法一(已知元素的高宽):
#div1 {
background-color: #6699FF;
width: 200px;
height: 200px;
position: absolute; /* 父元素需要相对定位 */
top: 50%;
left: 50%;
margin-top: -100px; /* 二分之一的height */
margin-left: -100px; /* 二分之一的width */
}
方法二:
#div1 {
width: 200px;
height: 200px;
background-color: #6699FF;
margin: auto;
position: absolute; /* 父元素需要相对定位 */
left: 0;
top: 0;
right: 0;
bottom: 0;
}
对于垂直居中一个 <img>
,可以使用更简便的方法:
#container {
display: flex;
justify-content: center;
align-items: center;
}
上述代码将 <img>
元素放置在一个容器中(#container
),通过使用 Flex 布局的 justify-content: center;
和 align-items: center;
属性,实现了图片在容器中的垂直居中效果。
THE END
暂无评论内容