css背景图像没有在DIV中显示

Sam*_*Sam 3 html css background-image

如果我这样做:

.floatingBox div div {
   text-align: center;
   position: relative;
   background-image: url('../images/car.png');
   background-repeat: no-repeat;
   background-position: center;
}

<div class='floatingBox'>
    <div class='effect2'>
        <a href=/Devis/moto><div class='motorbike'></div></a>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

然后背景图像显示正常.

但是,如果我这样做:

.floatingBox div div {
   text-align: center;
   position: relative;
   background-repeat: no-repeat;
   background-position: center;
}

.motorbike {
    background-image: url('../images/moto.png');
}
Run Code Online (Sandbox Code Playgroud)

然后,背景图像不再显示.

怎么会 ?

abb*_*ood 5

尝试将你的HTML更改为

<div class='floatingBox'>
    <div class='effect2'>
        <a href='/Devis/moto' class='motorbike'></a>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

和你的css

.motorbike {
    display: block;
    position: relative;
    background-image: url('../images/car.png');
    background-repeat: no-repeat;
    background-position: center;

    width: /* put a non-zero width value here */ ;
    height: /* put a non-zero height value here */ ;
}
Run Code Online (Sandbox Code Playgroud)

解释:一个<a>标签可以采取的地方<div>,如果你设置它的display属性来阻止标签.(<a>默认display:inline)

你也想设置宽度和高度,因为该div内没有内容.

一般来说,避免级联你的CSS风格是一个好主意..请看这里详细讨论