css中图片居中显示的代码怎么写
原创css 中可使用以下代码水平居中图片:设置容器元素 text-align: center;。将图片设为内联块级元素 display: inline-block;。使图片垂直居中 vertical-align: middle;。垂直居中图片:将容器元素设为 flexbox display: flex;。使子元素垂直居中 align-items: center;。使子元素水平居中 justify-content: center;。限制图片大小 max-width: 100%;,max-height:
CSS 中图片居中显示代码
问题:如何使用 CSS 代码让图片在元素中水平和垂直居中显示?
回答:
水平居中
立即学习“前端免费学习笔记(深入)”;
.image-container { text-align: center; } .image { display: inline-block; vertical-align: middle; }
垂直居中
.image-container { display: flex; align-items: center; justify-content: center; } .image { max-width: 100%; max-height: 100%; }
详细说明:
水平居中
立即学习“前端免费学习笔记(深入)”;
- text-align: center; 将 image-container 元素设置为水平居中。
- display: inline-block; 将 image 元素设为内联块级元素,允许它与文本对齐。
- vertical-align: middle; 将 image 元素在垂直方向上居中,与 surrounding text 对齐。
垂直居中
- display: flex; 将 image-container 元素设为 flexbox,允许对其子元素进行灵活布局。
- align-items: center; 将 image-container 元素中的所有子元素在垂直方向上居中。
- justify-content: center; 将 image-container 元素中的所有子元素在水平方向上居中。
- max-width: 100%; 和 max-height: 100%; 限制 image 元素的大小,使其适应 image-container 元素的大小并保持纵横比。
以上就是css中图片居中显示的代码怎么写的详细内容,更多请关注IT视界其它相关文章!
上一篇:css取消下划线怎么弄 下一篇:css怎么让文字显示在图片上