简体   繁体   中英

css background image not showing in DIV

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 ?

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

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

在第一眼看来,您的锚和链接似乎没有任何内容,因此隐含有0px的宽度和高度。

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM