Skip to content
Fix Code Error

Set size on background image with CSS?

March 13, 2021 by Code Error
Posted By: Anonymous

Is it possible to set the size of the background image with CSS?

I want to do something like:

background: url('bg.gif') top repeat-y;
background-size: 490px;

But it seems it’s totally wrong to do it like that…

Solution

CSS2

If you need to make the image bigger, you must edit the image itself in an image editor.

If you use the img tag, you can change the size, but that would not give you the desired result if you need the image to be background for some other content (and it will not repeat itself like you seems to want)…

CSS3 unleash the powers

This is possible to do in CSS3 with background-size.

All modern browsers support this, so unless you need to support old browsers, this is the way to do it.
Supported browsers:

Mozilla Firefox 4.0+ (Gecko 2.0+), Microsoft Internet Explorer 9.0+, Opera 10.0+, Safari 4.1+ (webkit 532) and Chrome 3.0+.

.stretch{
/* Will stretch to specified width/height */
  background-size: 200px 150px;
}
.stretch-content{
/* Will stretch to width/height of element */
  background-size: 100% 100%;
}

.resize-width{
/* width: 150px, height: auto to retain aspect ratio */
  background-size: 150px Auto;
}
.resize-height{
/* height: 150px, width: auto to retain aspect ratio */
  background-size: Auto 150px;
}
.resize-fill-and-clip{ 
  /* Resize to fill and retain aspect ratio.
     Will cause clipping if aspect ratio of box is different from image. */ 
  background-size: cover;
}
.resize-best-fit{
/* Resize to best fit and retain aspect ratio.
   Will cause gap if aspect ratio of box is different from image. */ 
  background-size: contain;
}

In particular, I like the cover and contain values that gives us new power of control that we didn’t have before.

Round

You can also use background-size: round that have a meaning in combination with repeat:

.resize-best-fit-in-repeat{
/* Resize to best fit in a whole number of times in x-direction */ 
  background-size: round auto; /* Height: auto is to keep aspect ratio */
  background-repeat: repeat;
}

This will adjust the image width so it fits a whole number of times in the background positioning area.


Additional note
If the size you need is static pixel size, it is still smart to physically resize the actual image. This is both to improve quality of the resize (given that your image software does a better job than the browsers), and to save bandwidth if the original image is larger than what to display.

Answered By: Anonymous

Related Articles

  • Reference - What does this regex mean?
  • GLYPHICONS - bootstrap icon font hex value
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Vuetify v-tabs v-tab-item overflows window width
  • After a little scroll, the sticky navbar just is not…
  • Is it possible to apply CSS to half of a character?
  • Form field border-radius is not working only on the…
  • How to show title in hover - css / jquery
  • SQL Server - find nth occurrence in a string
  • Navbar not filling width of page when reduced to mobile view
  • Having trouble with my nav bar/header, It used to…
  • “tag already exists in the remote" error after…
  • Unity Scripts edited in Visual studio don't provide…
  • Logging best practices
  • What is the worst programming language you ever worked with?
  • Active tab issue on page load HTML
  • Use of Jquery on scroll event
  • What are the different usecases of PNG vs. GIF vs.…
  • VueJS and tinyMCE, custom directives
  • jQuery.on() Delegation: Slightly complex selector…
  • How to use html template with vue.js
  • CKEditor setData not clearing or changing text in rte
  • How to resolve…
  • show all tags in git log
  • What is your most productive shortcut with Vim?
  • CSS grid wrapping
  • Script for Mouseover to let GIF finish before…
  • How to use Svelte store with tree-like nested object?
  • how do i remove the onclick function after clicking once
  • How to vertically align an image inside a div
  • Smart way to truncate long strings
  • loop and eliminate unwanted lines with beautiful soup
  • Jquery fadeToggle Trouble
  • Getting Monaco to work with Vuejs and electron
  • How do I return the response from an asynchronous call?
  • Start redis-server with config file
  • How to stretch the div to all the height of the page?
  • In Polymer 2.0 how to observe edits to properties of…
  • Identifying and solving…
  • Using Auto Layout in UITableView for dynamic cell…
  • How to filter a RecyclerView with a SearchView
  • Why my "title" bloc doesn't go to bottom?
  • Adobe XD to responsive html
  • What does "Fatal error: Unexpectedly found nil while…
  • When I use '/js/app.js' on my Laravel view my…
  • Stop a gif animation onload, on mouseover start the…
  • Javascript text animation not triggering
  • Dynamically replace img src attribute with jQuery
  • What is git tag, How to create tags & How to…
  • Centering in CSS Grid
  • How to use java.net.URLConnection to fire and handle…
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • What's the difference between including files with…
  • How can I use/create dynamic template to compile…
  • What does do?
  • How to dispatch a Redux action with a timeout?
  • Azure Pipelines compare Key Vault Secrets in Condition
  • How to create a temporary table in SSIS control flow…
  • jQuery override default validation error message…
  • How to recover stashed uncommitted changes
  • Adding a guideline to the editor in Visual Studio
  • Best practice multi language website
  • What is the difference between bottom-up and top-down?
  • Polymer Behaviors sharing properties
  • Text size and different android screen sizes
  • How can I manually compile a svelte component down…
  • Usage of __slots__?
  • How can I find the product GUID of an installed MSI setup?
  • why my css code is not working in vuejs?
  • Set up DNS based URL forwarding in Amazon Route53
  • What's the best way of scraping data from a website?
  • How to download and save an image in Android
  • How to load GIF image in Swift?
  • GUI-based or Web-based JSON editor that works like…
  • What are the nuances of scope prototypal /…
  • What is causing this broken animation/transition in…
  • In CSS Flexbox, why are there no "justify-items" and…
  • How to handle Vue 2 memory usage for large data (~50…
  • What does a "Cannot find symbol" or "Cannot resolve…
  • Memcached vs. Redis?
  • Javascript validate all checkboxes are selected
  • What is the JSF resource library for and how should…
  • How do I keep only the first map and when the game…
  • What is JSON and why would I use it?
  • Fontawesome fonts not loading using Aurelia, with…
  • apache server reached MaxClients setting, consider…
  • Plotting a 3D array second by second without…
  • What is an optional value in Swift?
  • Polymer 1.0 'array-style' path accessors,…
  • How to use Servlets and Ajax?
  • How to preserve space occupied by status bar when…
  • Use vue-html-editor in vue-component
  • Download a file with Android, and showing the…
  • When trying to insert a table into a quill editor I…
  • "Thinking in AngularJS" if I have a jQuery background?
  • Adding gif image in an ImageView in android
  • What is a NullReferenceException, and how do I fix it?
  • Getting navigation duplicated error while the route…
  • biblatex: splitting bibliography entry which are…
  • What is an IndexOutOfRangeException /…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to flush output of print function?

Next Post:

Convert Rows to columns using ‘Pivot’ in SQL Server

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error