问题:图片大小未知,如何让图片在div中居中
给div设置一个背景颜色,方便观察居中效果
div{ background-color: lawngreen; }
让图片在div中水平居中的方法
div{ text-align: center; }
让图片在div中垂直居中的方法
方法一
div{ line-height: 500px; } img{ vertical-align: middle; }
方法二
div{ display: table-cell; vertical-align: middle; }
方法三
div{ display: flex; align-items: center; }
让图片在div中垂直水平居中
方法一
div{ text-align: center; line-height: 500px; } img{ vertical-align: middle; }
方法二
扫描二维码关注公众号,回复:
1660744 查看本文章
div{ text-align: center; display: table-cell; vertical-align: middle; }
方法三
div{ display: flex; /*水平居中*/ justify-content: center; /*垂直居中*/ align-items: center; }
方法四
div{ position: relative; } img{ position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; }
上面四种方法结果都实现图片垂直水平居中,结果如下: