Flexbox无法作用于背景图片?求助CSS背景图居中方案
背景图片无法居中的问题修复
你的代码里有两个核心问题导致背景图没正常显示:
- HTML结构错误:带
angryjalapeno类的div被放在了<head>标签里,浏览器不会渲染<head>中的页面元素,所以这个容器根本没被加载到页面里。 - 多余的Flex属性:
display: flex、justify-content、align-items是用来控制容器内部子元素布局的,对背景图片完全无效,这些属性可以直接删掉。
修正后的完整代码:
HTML代码:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Background as color and image</title> <link rel="stylesheet" href="css/style.css"> </head> <body> <div class="angryjalapeno"></div> </body> </html>
CSS代码:
.angryjalapeno { width: 500px; height: 300px; background-image: url(https://placehold.co/200x200); background-repeat: no-repeat; background-position: center; background-size: cover; }
补充说明:
- 把div移到
<body>内后,容器才会被浏览器正常渲染,背景图也能正常显示出来。 background-position: center已经可以让背景图在容器内水平、垂直双居中,background-size: cover是让图片按比例铺满容器,如果不需要铺满,也可以换成contain或者具体的宽高值。
内容的提问来源于stack exchange,提问作者thekingofwands
相关产品推荐
相关产品推荐

