简体   繁体   中英

CSS 'background-image' not resizing correctly

I'm in the midst of making a navigation bar. I came here earlier and got some help re-organising and coding said item. All seemed great and it seemed like it should work but when using the following code instead of each image resizing, it only showed X% of the images height and Y% of the images width. I cannot figure out what is going wrong.

CSS:

#navbar a.newr:link { background-image: url('newr.png'); display: block; width: 5%; height: 2%; }

#navbar a.newr:hover { background-image: url('newrhover.png'); display: block; width: 5%; height: 2%; }

Please refer to how it looks looks on my website to see what I mean. Please also refer to my other navbar question.

Thank you.

Background images don't resize. They are shown in full size and are clipped if the container is smaller.

What you can do:

  • The best approach is to resize the images to the target size
  • A hackish approach is to use absolutely positioned <img> tags as background and <span> text as foreground.

     <div class="hasBg"> <img> <span>text</span> <div> .hasBg{ position:relative; } //will autofit depending on how span stretches the container .hasBg img{ position:absolute; top: 0; bottom: 0; left: 0; } .hasBg span{ position:absolute; } 
  • A native but new feature is to use the new CSS3 background-size . but this is not cross-browser afaik

Since you've done it as a background image, the width and height attributes only apply to the div, not the image.

You have two options.

  • Resize your images to fit the dimensions
  • have your images on your page and use javascript for your hover effect

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