css background image not showing in DIV

我怕爱的太早我们不能终老 提交于 2019-12-10 10:15:21

问题


If I do that:

.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>

then the background image shows up fine.

However if I do:

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

.motorbike {
    background-image: url('../images/moto.png');
}

then, the background image does not show up any longer.

How come ?


回答1:


try changing you html to

<div class='floatingBox'>
    <div class='effect2'>
        <a href='/Devis/moto' class='motorbike'></a>
    </div>
</div>

and your css to

.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 */ ;
}

explanation: an <a> tag can take the place of a <div> tag if you set its display property to block.. (<a> defaults to display:inline)

you also want to set the width and height since there is no content inside that div.

in general its a good idea to avoid cascading in your css styles.. see here for a detailed discussion of that




回答2:


You should not put a div inside a link tag. Put it outside.




回答3:


At the first look it seems that your anchor and link don't have any content so implicit there is 0px width and height.




回答4:


Well first of all your div closing tag is inside anchor tag. Second of all, there's no content displaying inside your anchor tag (it's just empty tag, so it doesn't have dimensions etc.), which means exactly like there's no text in your link tag - making it hidden (since there's nothing to display)



来源:https://stackoverflow.com/questions/15106808/css-background-image-not-showing-in-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!