Set Div Width For Css Background Image Width?

Is there a clean CSS way to set the width of a div to the width of the background image you use for this div?

For example, right now I am doing this ...

#homeNav{

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

}
#aboutNav{

    background-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 would not want to write the width of each div.

Any suggestions?

+3
source share
2 answers

Unfortunately no, no. CSS does not know the width of the specified background images. You can do this with a bit of Javascript, which preloaded the images and then set the width of the div.

+3
source

What I've done:

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

, : p

+3

Source: https://habr.com/ru/post/1756301/


All Articles