CSS Background Image To Fit Width, Height Should Auto-scale In ...

Sorry, we no longer support your browser Please upgrade to Microsoft Edge, Google Chrome, or Firefox. Learn more about our browser support. Just browsing Stack Overflow? Help us improve your experience. Sign up for research
    1. Home
    2. Questions
    3. Tags
    4. Users
    5. Companies
    6. Labs
    7. Jobs
    8. Discussions
    9. Collectives
    10. Communities for your favorite technologies. Explore all Collectives

  1. Teams

    Ask questions, find answers and collaborate at work with Stack Overflow for Teams.

    Try Teams for free Explore Teams
  2. Teams
  3. Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Get early access and see previews of new features.

Learn more about Labs CSS background image to fit width, height should auto-scale in proportion Ask Question Asked 12 years, 9 months ago Modified 1 year, 2 months ago Viewed 1.1m times 472

I have

body { background: url(images/background.svg); }

The desired effect is that this background image will have width equal to that of the page, height changing to maintain the proportion. e.g. if the original image happens to be 100*200 (any units) and the body is 600px wide, the background image should end up being 1200px high. The height should change automatically if the window is resized. Is this possible?

At the moment, Firefox looks like it's making the height fit and then adjusting the width. Is this perhaps because the height is the longest dimension and it's trying to avoid cropping? I want to crop vertically, then scroll: no horizontal repeat.

Also, Chrome is placing the image in the centre, no repeat, even when background-repeat:repeat is given explicitly, which is the default anyway.

Share Improve this question Follow asked Feb 13, 2012 at 15:14 spraff's user avatar spraffspraff 33.2k26 gold badges133 silver badges251 bronze badges 2
  • 4 Does html, body { height: 100%; } help? Also, cough. – thirtydot Commented Feb 13, 2012 at 15:27
  • For anyone coming here trying to do this, you may also need to set preserveAspectRatio: "none" on your svg itself (edit its source). See stackoverflow.com/questions/11658173/… – brandonscript Commented Nov 12, 2021 at 14:54
Add a comment |

13 Answers 13

Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 1018

There is a CSS3 property for this, namely background-size (compatibility check). While one can set length values, it's usually used with the special values contain and cover. In your specific case, you should use cover:

body { background-image: url(images/background.svg); background-size: cover; /* <------ */ background-repeat: no-repeat; background-position: center center; /* optional, center the image */ }

Eggsplanation for contain and cover

Sorry for the bad pun, but I'm going to use the picture of the day by Biswarup Ganguly for demonstration. Lets say that this is your screen, and the gray area is outside of your visible screen. For demonstration, I'm going to assume a 16x9 ratio.

screen

We want to use the aforementioned picture of the day as a background. However, we cropped the image to 4x3 for some reason. We could set the background-size property to some fixed length, but we will focus on contain and cover. Note that I also assume that we didn't mangle the width and/or height of body.

contain

contain

Scale the image, while preserving its intrinsic aspect ratio (if any), to the largest size such that both its width and its height can fit inside the background positioning area.

This makes sure that the background image is always completely contained in the background positioning area, however, there could be some empty space filled with your background-color in this case:

contain

cover

cover

Scale the image, while preserving its intrinsic aspect ratio (if any), to the smallest size such that both its width and its height can completely cover the background positioning area.

This makes sure that the background image is covering everything. There will be no visible background-color, however depending on the screen's ratio a great part of your image could be cut off:

cover

Demonstration with actual code

div > div { background-image: url(https://i.sstatic.net/r5CAq.jpg); background-repeat: no-repeat; background-position: center center; background-color: #ccc; border: 1px solid; width: 20em; height: 10em; } div.contain { background-size: contain; } div.cover { background-size: cover; } /******************************************** Additional styles for the explanation boxes *********************************************/ div > div { margin: 0 1ex 1ex 0; float: left; } div + div { clear: both; border-top: 1px dashed silver; padding-top:1ex; } div > div::after { background-color: #000; color: #fefefe; margin: 1ex; padding: 1ex; opacity: 0.8; display: block; width: 10ex; font-size: 0.7em; content: attr(class); } <div> <div class="contain"></div> <p>Note the grey background. The image does not cover the whole region, but it's fully <em>contained</em>. </p> </div> <div> <div class="cover"></div> <p>Note the ducks/geese at the bottom of the image. Most of the water is cut, as well as a part of the sky. You don't see the complete image anymore, but neither do you see any background color; the image <em>covers</em> all of the <code>&lt;div&gt;</code>.</p> </div>

Share Improve this answer Follow edited Nov 6, 2015 at 8:33 answered Feb 13, 2012 at 17:29 Zeta's user avatar ZetaZeta 106k13 gold badges202 silver badges245 bronze badges 7
  • This is exactly what I want, thanks. It doesn't seem to work in Chrome (or Chromium, at least) -- got any bright ideas? – spraff Commented Feb 14, 2012 at 12:40
  • According to quirksmode.org/css/contents.html#t44 it should work in Chrome without any prefix. However, have you tried the -webkit- prefix? – Zeta Commented Feb 14, 2012 at 12:54
  • 4 Yauhen's answer (at the bottom of this page) was actually what I was looking for: background-size: contain – Danny Beckett Commented Jul 18, 2013 at 2:30
  • 1 @DannyBeckett: While this is possible, it isn't what the OP was looking for: "I want to crop vertically, then scroll: no horizontal repeat." – Zeta Commented Jul 18, 2013 at 4:09
  • 4 contain is like zoom fit. cover is like zoom fill. contain adjusts image size to match the larger dimension among width and height. cover adjusts image size to match the smaller dimension among width and height. – ahnbizcad Commented May 26, 2014 at 2:01
| Show 2 more comments 48

Based on tips from https://developer.mozilla.org/en-US/docs/CSS/background-size I end up with the following recipe that worked for me

body { overflow-y: hidden ! important; overflow-x: hidden ! important; background-color: #f8f8f8; background-image: url('index.png'); /*background-size: cover;*/ background-size: contain; background-repeat: no-repeat; background-position: right; } Share Improve this answer Follow answered Jan 15, 2013 at 22:40 Yauhen Yakimovich's user avatar Yauhen YakimovichYauhen Yakimovich 14.2k8 gold badges61 silver badges68 bronze badges 2
  • 3 Although I used background-position: center;, this did work better for me than backgound-size: cover;. – Nate Commented Apr 26, 2013 at 4:50
  • 1 May I know why we need the overflow-y: hidden part? – Nam G VU Commented Aug 17, 2017 at 7:37
Add a comment | 31

Background image is not Set Perfect then his css is problem create so his css file change to below code

html { background-image: url("example.png"); background-repeat: no-repeat; background-position: 0% 0%; background-size: 100% 100%; }

%; background-size: 100% 100%;"

Share Improve this answer Follow answered May 26, 2017 at 7:14 jignesh vasoya's user avatar jignesh vasoyajignesh vasoya 3833 silver badges4 bronze badges Add a comment | 14

I'm not sure what you're looking for exactly, but you really should check out these excellent blog posts written by Chris Coyier from CSS-Tricks:

http://css-tricks.com/how-to-resizeable-background-image/

http://css-tricks.com/perfect-full-page-background-image/

Read the descriptions for each of the articles and see if they're what you're looking for.

The first answers the following question:

Is there a way to make a background image resizeable? As in, fill the background of a web page edge-to-edge with an image, no matter the size of the browser window. Also, have it resize larger or smaller as the browser window changes. Also, make sure it retains its ratio (doesn't stretch weird). Also, doesn't cause scrollbars, just cuts off vertically if it needs to. Also, comes in on the page as an inline tag.

The second post's goal is to get the following, a "background image on a website that covers the entire browser window at all times. "

Hope this helps.

Share Improve this answer Follow answered Feb 13, 2012 at 16:49 element119's user avatar element119element119 7,6259 gold badges52 silver badges77 bronze badges Add a comment | 12 body{ background-image: url(../url/imageName.jpg); background-attachment: fixed; background-size: auto 100%; background-position: center; } Share Improve this answer Follow answered Oct 8, 2018 at 9:34 Adriaan Mouton's user avatar Adriaan MoutonAdriaan Mouton 3053 silver badges3 bronze badges 1
  • 21 describe what is the problem exactly and how you solve it, please don't paste a bunch of code here without explanation. – Siavash Commented Oct 8, 2018 at 9:37
Add a comment | 10

Just add this one line:

.your-class { height: 100vh; }

vh is viewport height. This will automatically scale to fit the device' browser window.

Check more here: Make div 100% height of browser window

Share Improve this answer Follow edited Nov 9, 2017 at 9:44 answered Mar 27, 2017 at 12:51 Kaka Ruto's user avatar Kaka RutoKaka Ruto 5,0851 gold badge35 silver badges40 bronze badges Add a comment | 7

Try this,

element.style { background: rgba(0, 0, 0, 0) url("img/shopping_bgImg.jpg") no-repeat scroll center center / cover; } Share Improve this answer Follow edited Jul 29, 2015 at 6:57 Sagar Naliyapara's user avatar Sagar Naliyapara 4,1315 gold badges42 silver badges62 bronze badges answered Jul 29, 2015 at 5:57 Laxman Maurya's user avatar Laxman MauryaLaxman Maurya 971 silver badge3 bronze badges 0 Add a comment | 1

I had the same issue, unable to resize the image when adjusting browser dimensions.

Bad Code:

html { background-color: white; background-image: url("example.png"); background-repeat: no-repeat; background-attachment: scroll; background-position: 0% 0%; }

Good Code:

html { background-color: white; background-image: url("example.png"); background-repeat: no-repeat; background-attachment: scroll; background-position: 0% 0%; background-size: contain; }

The key here is the addition of this element -> background-size: contain;

Share Improve this answer Follow answered Jan 15, 2014 at 19:21 CodingWoodsman's user avatar CodingWoodsmanCodingWoodsman 811 silver badge5 bronze badges Add a comment | 1

Here's what worked for me:

background-size: auto 100%; Share Improve this answer Follow edited Aug 16, 2017 at 15:47 Koby Douek's user avatar Koby Douek 16.7k20 gold badges78 silver badges109 bronze badges answered Aug 16, 2017 at 15:38 Danny McMurray's user avatar Danny McMurrayDanny McMurray 191 bronze badge Add a comment | 1

if you set min-height, for example:

min-height: 100vh;

You can use the below code to fit your background easily

body { background: url(images/background.svg); min-height: 100vh; background-repeat: no-repeat; background-size: cover; } Share Improve this answer Follow edited Sep 1, 2022 at 8:56 Evan Rusackas's user avatar Evan Rusackas 6145 silver badges6 bronze badges answered Aug 27, 2022 at 4:10 Ruwan Pathirana's user avatar Ruwan PathiranaRuwan Pathirana 1471 silver badge10 bronze badges Add a comment | 0 width: 100%; height: 100vh; background: url("../img/hero-bg.jpg") top center; background-size: cover; background-repeat: no-repeat; background-position: 0% 0%; background-size: 100% 100%; Share Improve this answer Follow answered Jul 16, 2022 at 16:51 SamirPaul's user avatar SamirPaulSamirPaul 92 bronze badges 1
  • 3 Please read How do I write a good answer?. While this code block may answer the OP's question, this answer would be much more useful if you explain how this code is different from the code in the question, what you've changed, why you've changed it and why that solves the problem without introducing others. – Saeed Zhiany Commented Jul 17, 2022 at 3:48
Add a comment | -1

Use background-size cover property to fill the page. use background position, attachment, and repeat for background adjustments...

html { background: url(https://cdn.pixabay.com/photo/2023/08/11/04/41/woman-8182795_1280.jpg); background-position: center center; background-attachment: fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; background-repeat: no-repeat; }

Share Improve this answer Follow answered Sep 4, 2023 at 16:43 manoj's user avatar manojmanoj 1871 silver badge8 bronze badges Add a comment | -5

Setting background size does not help, the following solution worked for me:

.class { background-image: url(blablabla.jpg); /* Add this */ height: auto; }

It basically crops the image and makes it fit in, background-size: contain/cover still didn't make it fit.

Share Improve this answer Follow edited Jan 8, 2018 at 0:03 Omar Einea's user avatar Omar Einea 2,5247 gold badges24 silver badges36 bronze badges answered Jan 7, 2018 at 16:36 anonymous's user avatar anonymousanonymous 1 Add a comment |

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid …

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.

Draft saved Draft discarded

Sign up or log in

Sign up using Google Sign up using Email and Password Submit

Post as a guest

Name Email

Required, but never shown

Post Your Answer Discard

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.

  • Featured on Meta
  • We’re (finally!) going to the cloud!
  • More network sites to see advertising test [updated with phase 2]
Visit chat

Linked

1 Set a background image width & height, with aspect ratio 2697 How to make a div 100% height of the browser window 939 Stretch and scale a CSS image in the background - with CSS only 80 CSS background image to fit height, width should auto-scale in proportion 69 How does one make a SVG background that stretches rather than tiles? 4 How to print an image completely filling an A4 or other format? 4 HTML/CSS - Make background fit any window size 3 CSS make a width:100% stop against floating objects 4 Size Background Image to fit browser window JavaScript/HTML/CSS/JQuery 0 HTML DIV background See more linked questions 2 How to make background-image size maintain its proportions? 0 scale background image according to width and height of div CSS 80 CSS background image to fit height, width should auto-scale in proportion 1 Background Image That Adjusts to Screen Width Constraining Proportions 2 Scale Background Image Height Based on Width 29 Scale div to fit background image 1 My perfect background image 0 Auto-scale Background Image 2 Background image full width and height 0 scale background image in div depending on screen size

Hot Network Questions

  • driver "self['prop']" not working in 4.2.2?
  • Simple successor gate
  • What does "Ganz wirklich ehrlich" mean in this context?
  • Why does "not" stand after "it" in "he knows it not"?
  • Gen 25:8 Difference between translations
  • Formative alternative to midterms for a large class
  • A fantasy movie with two races, "Big Ones" (=us) and smaller ones, about saving a newborn baby from a cruel queen
  • Why is MacBook Air trackpad spanning to completely separate system?
  • Is it allowed to write a vacuous truth using the present tense but not the past subjunctive?
  • Baskervaldx doesn’t allow certain glyphs
  • DOS (density of states) in the vicinity of a band extremum point
  • How to make seal on lever flip-top "Kilner" jars without spoiling sterilization?
  • Prospective employers tell me my field is obsolete. How can I reinvent myself?
  • How to make an arrow leap over another to prevent their intersections in Tikz?
  • Does .htaccess alone offer an authentication method that offers "remember me" and custom titles?
  • If LATERAL is optional for table-valued functions, then why does this query error without it?
  • In AES GCM, would using different nonces that are close reveal data?
  • What's the contrary of formation as in the opposite of the process of formation?
  • Apple falling from boat mast
  • Use of “12 m.” for noon and “12 p.m.” for midnight
  • Connectedness of complement of intersection of two balls
  • relative pronouns and their order in instruction manuals
  • Looking for short story about detectives investigating a murder in the future
  • Is there a Linux utility to allow users to request new passwords?
more hot questions Question feed Subscribe to RSS Question feed

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

lang-html

Từ khóa » Html Background Image Original Size