带边框、居中logo的div添加背景图时布局损坏如何解决?
问题原因
- 引号嵌套冲突:div的style属性用双引号包裹,而
background-image: url("imageurl")内部同样使用了双引号,会直接截断style属性的解析,后续设置的宽度、高度、flex布局等所有样式都不会生效,直接导致布局错乱。 - 背景属性覆盖:你先声明了
background-image,后面又写了background: #fff,background是复合属性,会直接覆盖之前单独设置的所有背景相关属性,就算引号问题解决,背景图也不会正常显示。
修复后的代码
<div style=" float: left; width: 300px; border-radius: 25px; border: 2px solid #000000; height: 150px; position: relative; background-color: #fff; background-image: url('你的背景图地址'); background-size: cover; background-position: center; background-repeat: no-repeat; display: flex; align-items: center; justify-content: center;"> <img style="border-radius: 50%; height: 50%;" src="logo图片地址" /> </div>
补充说明
如果需要调整背景图的显示效果,可以修改background-size的属性值:
- 用
contain可以让背景图完整显示在盒子内,不会被裁剪 - 用具体的百分比或者像素值可以自定义背景图尺寸
内容的提问来源于stack exchange,提问作者piguy
相关产品推荐
相关产品推荐

