css-图片居中-垂直和水平居中
响应式布局里的图片的居中
So in this post, I will be showing some of the most common ways to center an image both vertically and horizontally using different CSS properties.
So in this post, I will be showing some of the most common ways to center an image both vertically and horizontally using different CSS properties.
position: static | relative | absolute | fixed | sticky
position: static 是默认的value
position: sticky 是 position: relative 和 position: fixed的混合。
先看水平居中
1. 图片水平居中: 图片外部容器div设置文本对齐为居中。
<style>
div {
text-align: center;
}
</style>
<div>
<img src='your.jpg'>
</div>2. 另外一种设置图片容器div的方式是用:flex
div {
display: flex;
justify-content: center;
}
img {
width: 60%;
}3. 设置图片本身属性
img本身默认属于display:inline , 要设置水平对齐,需要设置自动左右边距,也就是 left-margin和right-margin, 通过margin:auto实现 左右边距相等。
img {
margin: auto;
display: block;
}img {
width: 60%;
margin: auto;
display: block;
}1和2属于容器属性设置。3主要设置图片属性, display:flex 不支持一些少数的老浏览器。
如何垂直居中呢?
1. 用display:flex话的就比较简单。 display:flex 本身是一维的排列, 可设置为垂直居中的 align-items: center 排列items: center。这里也可以底部对齐,顶部对齐等。
div {
display: flex;
justify-content: center;
align-items: center;
height: 800px;
}
img {
width: 60%;
height: 500px;
}2. 采用position: absolute 和 transform 属性
先定义容器 position: relative; 相对位置
再定义图片 position: absolute; 绝对位置
定义图片的从哪开始: top: 50%, left: 50%; 这时候图片从中心点开始,那就不是居中了。还需要一个转换 transform: translate(-50%, -50%); 这里面的-50% 也是本元素的-50%, 也就是向上和向左分别移动50%, 保证图片的中心点= 容器的中心点。
img {
width: 80%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}阅读量: 1134
发布于:
修改于:
发布于:
修改于: