开发者

Set Div Width to Background Image Width Css?

开发者 https://www.devze.com 2023-01-08 10:41 出处:网络
Is there a pure css way of setting your div width to the width of the background image you are using for that div?

Is there a pure css way of setting your div width to the width of the background image you are using for that div?

for instance right now I'm doing this...

#homeNav{

    background-image:url(../images/navPieces/home.jpg);
    width:165px;
    text-align:right;

}
#aboutNav{

    background-开发者_C百科image:url(../images/navPieces/about.jpg);
    width:81px;
    text-align:center;

}
#competitorsNav{

    background-image:url(../images/navPieces/competitors.jpg);
    width:117px;
    text-align:center;
}

I'd love to NOT have to write in the width of every div.

Any suggestions?


What I did :

  • set the backgound-image to the div with url(urlsrc)
  • add an img to the div with src=urlsrc
  • get img size with .width() and .height()
  • remove the img
  • set css width and height of the div to the width and height precedently calculated

Ugly, but it works :p


Unfortunately no, there isn't. The CSS doesn't know the width of specified background images. You could do it with a bit of Javascript that preloaded the images and then set the div widths.


.parent {
    object-fit: contain;
    background-size: contain;
    background-repeat: no-repeat;
    max-width: 100%;
}

.parent1 {
 background-image: url("https://www.image-engineering.de/content/products/charts/te169/images/TE169.jpg");
}

.transparent-img{
    max-height:360px;
    opacity: 0;
}
 
<div class="parent parent1" id="homeNav">
   <img class="transparent-img" src="https://www.image-engineering.de/content/products/charts/te169/images/TE169.jpg">
 </div>  

Nice hacky answer was provided by oued but here is what I did with pure CSS.

You set your backgorund-size property to contain and not repeat. You set background-url as separate class on same parent element. Then you set opacity to 0 for image that will be inside parent element. This way your div will fallow width of transparent image and your background image will be shown and it will scale nicely.

0

精彩评论

暂无评论...
验证码 换一张
取 消