How to get width of device (not viewport)? - html

I'm making my first website and my meta tag just defines a constant width instead of taking the device width, because I am having fun with CSS animations and wanted to avoid making it dynamic. Most of it looks fine on mobile except things that need to be centered. When I center it based on percentages, it centers based on the width I set (my viewport) as opposed to the width of the device. This is not a bug, of course, but I was wondering if there was a way for me to get the width of the device even if I don't set it as the viewport, so I can just calculate the left attribute to center it. Any ideas? Thanks!
I didn't put code because there really aren't any issues, it is more of a how-to question.

To find the current width of your html body (device), you can try this javascript code window.innerWidth;
Try running this code and resize your windows to different widths:
function myFunction() {
var wid = window.innerWidth;
document.getElementById("display").innerHTML = "Width: " + wid;
}
<button onclick="myFunction()">Show</button>
<div id="display"></div>
ps: click on Run Code and then click on full page so you can resize your browser and test my snippet. It will show you the current width.

Sometimes some users do not maximize their browsers when it comes to desktop devices. But you can try taking the "body" width of your application by creating a variable. Something more advanced is to check if there is any positive variation of that value during navigation. On mobile devices that value would be a bit more precise, unless the screen is rotated.
your_var_name = document.body.clientWidth

I recommend flex css attribute.
https://css-tricks.com/snippets/css/a-guide-to-flexbox/
html
<div class="wrapper">
wrapper
<div class="inner"> inner </div>
</div >
css
.wrapper {
display: flex;
justify-content: center;
width: 200px;
}
.wrapper .inner {
width: 50px;
}
or
Using absolute and relative
wrapper {
position: absolute;
width: 200px;
}
wrapper parent {
position: relative;
width: 50px;
left: calc( 100% - 25px );
}

Related

Is there a way to reference the value of one css property in another css property? [duplicate]

This question already has answers here:
100vw causing horizontal overflow, but only if more than one?
(8 answers)
Closed 4 months ago.
As mentioned in the title, is it possible to calculate the vw without the scrollbars in css only?
For example, my screen has a width of 1920px. vw returns 1920px, great. But my actual body width is only something like 1903px.
Is there a way for me to retrieve the 1903px value with css only (not only for direct children of the body), or do I absolutely need JavaScript for this?
One way to do this is with calc. As far as i know, 100% is the width including scrollbars. So if you do:
body {
width: calc(100vw - (100vw - 100%));
}
You get the 100vw minus the width of the scrollbar.
You can do this with height as well, if you want a square that's 50% of the viewport for example (minus 50% of the scollbar width)
.box {
width: calc(50vw - ((100vw - 100%)/2))
height: 0
padding-bottom: calc(50vw - ((100vw - 100%)/2))
}
I do this by adding a line of javascript to define a CSS variable once the document has loaded:
document.documentElement.style.setProperty('--scrollbar-width', (window.innerWidth - document.documentElement.clientWidth) + "px");
then in the CSS you can use var(--scrollbar-width) to make any adjustments you need for different browsers with/without scrollbars of different widths. You can do something similar for the horizontal scrollbar, if needed, replacing the innerWidth with innerHeight and clientWidth with clientHeight.
COPY & PASTE solution
Here is an easy drop-in solution based on user11990065's answer to set a css variable --scrollbar-width and keep it updated on resizes.
It also gets calculated on DOMContentLoaded and load events so that you don't have to worry about size changes during the initial rendering phase.
You can just copy and paste it to your code as it is vanilla JS (or wrap it in a 'script' tag and paste it directly into your HTML code:
function _calculateScrollbarWidth() {
document.documentElement.style.setProperty('--scrollbar-width', (window.innerWidth - document.documentElement.clientWidth) + "px");
}
// recalculate on resize
window.addEventListener('resize', _calculateScrollbarWidth, false);
// recalculate on dom load
document.addEventListener('DOMContentLoaded', _calculateScrollbarWidth, false);
// recalculate on load (assets loaded as well)
window.addEventListener('load', _calculateScrollbarWidth);
If you have dynamic height changes in your page that might show / hide the scrollbar, you might want to look into Detect Document Height Change with which you can trigger the recalculation also on height changes.
As the value is calculated with JS and set to a fixed value you can use it in calc operations in your CSS, like so:
.full-width {
width: calc(100vw - var(--scrollbar-width));
}
This will give .full-width exactly the available width.
According to the specs, the viewport relative length units do not take scrollbars into account (and in fact, assume that they don't exist).
So whatever your intended behavior is, you cannot take scrollbars into account when using these units.
body { overflow: overlay; }
If you don't want to overcomplicate things, this might be sufficient in certain situations. At least it fixed my issues well enough, since there was enough whitespace between the content and the viewport edges (Windows scrollbar would overlap your 20-ish most right pixels).
Webkit browsers exclude the scrollbars, other include them in the returned width.
This may of course lead to problems: for instance if you have dynamically generated content with ajax that add height dynamically, Safari might switch from a layout to another during page visualization...
Ok, it doesn't happen often, but it's something to be aware about.
On mobile, less problems, cause scrollbars are generally not showed.
That's said, if your problem is calculate exactly the viewport width without scrollbars in all browser, as far as i know, a good method is this:
width = $('body').innerWidth();
having previously set:
body {
margin:0;
}
100vw = width of the screen with scrollbar
100% = width of the screen without scrollbar
It is always preferable to use calc(100% - 50px) while measuring the screen width. Even on windows browsers where scrollbar is visible directly, return the screen width differently when compare with macOS browsers.
It's possible just very "ugly" looking.
First you need to have this script running to get the scrollbar width into a css variable:
document.documentElement.style.setProperty('--scrollbar-width', (window.innerWidth - document.documentElement.clientWidth) + "px");
Now for example if you want "real" 80vw do this:
calc(0.8 * (100vw - var(--scrollbar-width)));
"real" 40vw
calc(0.4 * (100vw - var(--scrollbar-width)));
As long as you're not expecting any actual horizontal scroll, you could use this:
body {
overflow-x: hidden;
}
Which will then just hide the tiny amount of horizontal scroll caused by the auto scrolling Y.
I came across this question while looking for an answer for my case.
I wanted to use WordPress's solution to center a div on the viewport with the viewport's width just like .alignfull would normally.
Situation:
<html>
<body>
<div class="main">
<div class="continer">
<div class="row">
<div class="col-12">
<article>
<div class="content">
<div class="alignfull-or-alignwide">
<p>The content.</p>
</div>
</div>
</article>
</div>
</div>
</div>
</div>
</body>
</html>
My solution:
html {
width: 100vw;
overflow-x: hidden;
}
.alignfull-or-wide {
margin-right: calc(50% - 50vw);
margin-left: calc(50% - 50vw);
width: 100vw;
max-width: 100vw; // change this for wide or w/e.
}
This solved my problem by making the root of the document as wide as the viewport. With this, you essentially ignore the width of any scrollbar.
By setting to 100vw we eliminate the width of the scrollbar on any platform.
By setting the overflow parameter, we prevent any content from being rendered outside of the viewport.
By setting margins, we center the left side of the div to it's relative positioned parent. This usually is the center of the viewport too.
Then, the negative margin pulls it to the left side of the viewport.
By doing the same on the right we create the illusion of the div being centered on the page.
Also something to watch out for: scrollbar-width on csswg.
The only way I found it to work without messing your code with "calc"
is to make the container element size to 100vw; Adding a wrapper around the container for overflow-x; This will make the container to be fullwidth like if the scrollbar was over the content.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html{ overflow-y: scroll; }
html, body{ padding:0; margin: 0;}
#wrapper{ overflow-x: hidden; }
.row{ width: 100vw; }
.row:after{ clear: both; content: ''; display: block; overflow: hidden; }
.row-left{ background: blue; float: left; height: 40vh; width: 50vw; }
.row-right{ background: red; float: right; height: 40vh; width: 50vw; }
</style>
</head>
<body>
<div id="wrapper">
<div class="row">
<div class="row-left"></div>
<div class="row-right"></div>
</div>
</div>
</body>
</html>
The vw unit doesn't take the overflow-y scrollbar into account when overflow-y is set to auto.
Change it to overflow-y: scroll; and the vw unit will be the viewport with the scrollbar. Then you can subtract the scrollbar size from the vw value using calc(). You can also define the scrollbar width, so it will be browser-independent.
Only downside to take into account. If the content fits into the screen, the scrollbar is shown anyway. Possible solution is to change from auto to scroll in javascript.
No, there's no way to calculate the vw without the scrollbars in CSS.
However, there's a way to solve the 100vw ruined by the scrollbar on Windows issue. You have to create a full-width element, in this case row--full-width, that beelds out of a Flex container. This solution works on both Mac and Windows:
HTML:
<section>
<div class="container">
<div class="row--full-width"></div>
<div class="row">
<div class="card">
</div>
<div class="card">
</div>
</div>
</div>
</section>
Example: https://jsfiddle.net/ecmv6ho1/show
Code: https://jsfiddle.net/ecmv6ho1/
As you can see in the example above, the row--full-width element bleeds out of the container, and it aligns with the header even when there's a scrollbar.
Tested on Edge 18 (Win), Edge 88 (Win/Mac), and Chrome 88 (Win/Mac).
The easiest way is set the html & body to 100vw:
html, body{ width:100vw; overflow-x: hidden; overflow-y: auto; margin: 0; }
The only problem is the right-most will be cut a little if scrollbar is shown.
If the case were something similar to a slider:
As posted in many answers, width 100% doesn't take into account the scrollbar, while 100vw does. In the case of having many elements that need to take the width of the window and that are nested inside a container already with 100% window width (or whose natural block width would be such), you can use:
Display flex for container
Flex: 0 0 100% for child elements
It's not my solution, but helps me create dropdown fullwidth menu with absolute in relative element in not fullwith span.
We should get scroll with in css var in :root and then use it.
:root{
--scrollbar-width: calc(100vw - 100%);
}
div { margin-right: var(--scrollbar-width); }
https://codepen.io/superkoders/pen/NwWyee

Prevent percentage resize after page load

I was wondering if it was a way to prevent resizing after the page has loaded. I have a header coded like this:
header {
position: fixed;
top: 0%;
left: 0%;
height: 60px;
width: 100%;
margin: 0% auto;
}
Can I prevent the width from resizing after the page has loaded, so that if someone zooms or resize their webpage, the header will remain at the 100% it was set to when the page was loaded?
Thanks in advance!
You will have to use some JS to set the width of the header element to a specific width so that re-size and zoom do not affect it.
Here is a jQuery solution using width.
<div>
<header class="to-fixed">Header</header>
</div>
div {
min-height: 250px;
background-color: #CCC;
}
header {
height: 50px;
background-color: yellow;
}
var $to_fixed = $( '.to-fixed' );
$to_fixed.width( $to_fixed.width() );
JSFiddle: https://jsfiddle.net/w9psx3t7/1
What happens here is we use JavaScript to tell us how wide the element is in pixels when it is at 100% width. Then we apply that width directly to the element via the style attribute. The width() method of jQuery allows us to retrieve and set the element's width. Since the width is set directly on the element it will override the default width value set by the CSS.
Notice that once the page has loaded the our JS has set the value and when you re-size the <header> element maintains it's width.
If you mean prevent the user from zooming in, then that's answered here: Prevent zoom cross-browser
And if you want to stop users from resizing their browser window (and generally keeping it the same size at all times) you can do something like:
window.addEventListener('resize', function() {
window.resizeTo(width, height);
});
Both are these are advised against though. I can't really see why you'd want this behaviour.
I don't know of a way to do this in CSS if you're setting the width to 100%. The simple way to do this in Javascript would be doing the following on page load:
var width = document.getElementsByTagName("header")[0].offsetWidth;
document.getElementsByTagName("header")[0].style.width = width;

Why does vw include the scrollbar as part of the viewport?

I'm trying to build a website that has lots of boxes that are of equal width and height. For example, I have a page that has 2 equal size boxes side by side.
The simple solution was to set the width and height to 50vw. This works great until there is a scroll bar. I've Googled around for hours and can't understand why on earth vw and vh would include the scrollbars as part of the viewport.
Here's a sample of my issue
HTML
<div class="container">
<div class="box red"></div>
<div class="box green"></div>
</div>
<div class="lotta-content"></div>
CSS
body {
margin: 0;
padding: 0;
}
.container {
width: 100vw;
}
.box {
float: left;
width: 50vw;
height: 50vw;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
.lotta-content {
height: 10000px;
}
Notice the unwanted horizontal scrollbar
https://jsfiddle.net/3z887swo/
One possible solution would be to use percentages for the widths, but vw for the height, but it won't ever be a perfect box which isn't the worst thing in the world, but still not ideal. Here's a sample
https://jsfiddle.net/3z887swo/1/
Does anyone know why vw/vh include scrollbars as part of the viewport? Also, if someone has a better solution than my own, I'd love to hear it. I'm looking for a pure CSS solution. I rather not have javascript.
I have a different answer, and feel the need to share my frustration
BECAUSE STANDARD-MAKERS ARE STUPID
(committees, in general, always are)
One simple (simplicistic) workaround is keeping the scrollbar always around and be dealt with it
html,body {margin:0;padding:0}
html{overflow-y:scroll}
(use overflow-x for a layout that uses vh)
I believe they seriously screwed the pooch on this one.
It would be convenient if viewport units didn't include cause scrollbars but it is the display size (screen) after all. Have look at this solution with a pseudo element though:
http://www.mademyday.de/css-height-equals-width-with-pure-css.html
Makes for a square in your example as well:
https://jsfiddle.net/3z887swo/4/
.box {
float: left;
width: 50%;
}
.box::before {
content: "";
display: block;
padding-top: 100%;
}
Edit - if anyone is wondering why this works (vertical padding responding to the original element's width)... that's basically how it's defined in the specification:
The percentage is calculated with respect to the width of the generated box's containing block, even for 'padding-top' and 'padding-bottom'.
http://www.w3.org/TR/CSS2/box.html#padding-properties
After coming across my own answer, I think it needed some refinement. Semantic ambiguity is why I replaced the word "include" with "cause" at the top. Because it's more the fact that vw units only take the viewport size into account - not including any scrollbar and causing overflow and a scrollbar in the other direction when its width is added to 100vw (making the total space that is needed the viewport plus scrollbar width, exceeding the screen).
As with the question here, the best way to handle vw units is likely to avoid them if you can because they just aren't very compatible with desktop browser (that don't have overlaying scrollbars).
I edited out the idea that included a CSS variable, however hopeful it seemed.
html { overflow-x: hidden; }
seems to work
This question is old, and answered well above, so I'm going to focus on obtaining scrollbar width to then be used to calc element widths, as that's why I landed here. Hopefully this will help other Googlers.
A sloppy CSS solution
I started writing the pure CSS solution based on the calculation below but once you start factoring in elements inside variable width containers, especially when they aren't 100% of the visible width, the calc functions start getting convoluted and unreadable.
For anybody interested, this calc on the root element (<html>) (assuming the doc is full width and no wider) will give you the scrollbar width or 0 when no scrollbar is displayed.
calc( 100vw - 100% );
A robust solution
Personally, I wouldn't battle CSS on this one. Use the right tool for the job:
(function get_scrollbar_width() {
// Get window width including scrollbar.
const withScrollBar = window.innerWidth;
// Get window width excluding scrollbar.
const noScrollBar = document.querySelector("html").getBoundingClientRect().width;
// Calc the scrollbar width.
scrollbarWidth = parseInt((withScrollBar - noScrollBar), 10) + 'px';
// Update the CSS custom property value.
let root = document.documentElement;
root.style.setProperty('--scrollbar', scrollbarWidth);
})();
:root {
--scrollbar: 0px;
}
body {
overflow: scroll;
}
.demobox {
display: grid;
grid: auto / var(--scrollbar) max-content;
width: calc(10em + var(--scrollbar) );
margin: 0 auto;
}
.demobox > div {
background: red;
}
.demobox > p {
padding: 1em;
text-align: center;
width: 10em;
}
<div class="demobox">
<div></div>
<p>
This red grid cell represents the scrollbar width as set
on the CSS custom property by the JavaScript function.
</p>
</div>
I have a solution here. It'll include the scrollbar width when you use 100vw, right? so if we can't make it right, then we can remove the scrollbar, make it invisible. like this: Hide scroll bar, but while still being able to scroll

Google Swiffy, and responsive design, height

I'm testing out Swiffy, and plugging it into Zurb's Foundation responsive framework. It all works well. I also updated the CSS for the #swiffycontainer container to have a width of width: 100%;.
The content fits nicely into the grid, but the my only issue is that if the size isn't set explicitly, then on a smaller screen, then, I get this issue with the height being way way larger than the content, even with height set at 500px. This also results in the Swiffy container showing contents outside of the stage.
Any ideas as to why? Would it be with the SVG generated from Swiffy? Thanks!
Update: It seems that this is probably related to AS 2/3's stageScale property on the Stage. Would anybody happen to know of a happy medium between "showAll/SHOW_ALL", and "noBorder/NO_BORDER"? Where the stage still resizes but doesn't show a border around it?
I ended up solving this issue with a bit of CSS that ensures that the height is scaled proportionally to the width (what ever width it maybe due to the responsive grid). This keeps the flash/Swiffy container from creating the letterbox bars.
In the SWF: Keep the default (AS2):
Stage.scaleMode = "noScale";
In the CSS, created a wrapper on the Swiffy container:
.swiffy-wrap {
position: relative;
width: 100%;
padding-bottom: 100%;
float: left;
height: 0;
}
On the Swiffy container
#swiffycontainer {
width : 100% !important;
height: 100% !important;
position: absolute;
left: 0;
}
just put in the html result of swiffy conversion width 100% be careful only width not height, height, like this
div id="swiffycontainer" style="width: 100%; height: 500px"
works for me

Alternative for background-size:cover in IE7+

I have a background image on the body of my web page. I have used background-size:cover so that the image stretches across the body whilst maintaining the aspect ratio of the image. I would like this to be the same for IE7 + IE8.
I have looked around and seen the following code:
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='AutumnWinter_4.jpg',
sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='AutumnWinter_4.jpg',
sizingMethod='scale')";
But this doesn't preserve the aspect ratio, which is really bad for the website we are aiming at.
Is there any way to do this? Without hitting up jQuery?
What's the reason of not using jQuery? You could load it in conditional comments for IE<8 only, so that for every other modern browser jQuery is not loaded.
Also consider that IE7 has a very low market share (2,52%, April 2012) so it can be acceptable to load ~ 25kb extra for that specific browser if this feature is so important for your site/application.
So, I've found this plugin for jQuery: https://github.com/louisremi/jquery.backgroundSize.js
A jQuery cssHook adding support for "cover" and "contain" to IE6-7-8, in 1.5K
See Github project page for more info.
backgroundSize.js will not actually stretch the bg image in IE7, it seems to just center it at the original size. See their demo and click on 'Check what IE6-7-8 users would normally see.'
#danRhul
I have read that backstretch will work in IE7+
Good luck!
You could just fake a background image with an actual image. It's a bit more HTML editing and certainly not ideal, but since when has handling IE ever been ideal?
<body>
<img id="mainBG" src="mainBG.jpg" />
<div id="content">
[ ... ]
Then style it accordingly
body{
position:relative;
}
#mainBG{
width:100%
position:absolute;
top:0px;
left:0px;
}
Should be cross-browser if I'm not mistaken.
I've used the following (http://css-tricks.com/perfect-full-page-background-image/) and it works well in ie7.
HTML:
<body>
<img class="bg" src="filename">
</body>
CSS:
.bg {
/* Set rules to fill background */
min-height: 100%;
min-width: 1024px;
/* Set up proportionate scaling */
width: 100%;
height: auto;
/* Set up positioning */
position: fixed;
top: 0;
left: 0;
}
#media screen and (max-width: 1024px) { /* Specific to this particular image */
img.bg {
left: 50%;
margin-left: -512px; /* 50% */
}
}
I know this is now an old question, but I thought I'd share a solution I came up with for anyone else who finds this question on google, like I did.
I was trying to get an image to cover a site's background and came across this question, however none of the solutions worked for me. I came up with this instead:
HTML: move the background image to an <img />, make it the first thing in your <body>.
<html>
<body>
<img class="background" src="kitty.jpg" />
<div class="content">
...
CSS: make the background appear under the content, set it's min-width/height to 100%.
html {
height: 100%
}
body .background {
position: absolute;
z-index: -1;
min-height: 100%;
min-width: 100%;
}
It's the min-height and min-width here that does the magic. Do not give the image a width and height in the HTML or CSS, or the aspect ratio will change.
The above will work for IE7 and IE8. If you would like to support IE6, you could set a centered image fallback like this:
CSS: If IE6, don't display the image, use a background image instead.
body {
_background: url("kitty.jpg") 50% top no-repeat;
}
body .background {
_display: none;
}
(N.B. If you don't like the underscore hack to target IE6, you could use conditionals instead – that's what the HTML5 Boilerplate does.)
After much trial and error, the best solution was guessing it!
The following worked for me.
body {
background-size:100%;
}
You have two options to achieve this with just CSS:
Use Object-fit: cover. The only problem with this is that it will not work in all browsers
If you want cross browser support, you can follow primitive CSS approach:
Position the image inside the container with absolute and then place it right at the centre using the combination:
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
Note:
Since transform ONLY works from IE9, you can make use of filters. Here is an answer for this.
Once it is in the centre, you can do,
// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;
// For Horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;
This makes the image get the effect of Object-fit:cover.
Here is a demonstration of the above logic.
https://jsfiddle.net/furqan_694/s3xLe1gp/
Unfortunately, most solutions to this kind of problem either depend on css3 or ignore the native functionality of "cover" that preserves the original aspect ratio of the image. https://github.com/louisremi/background-size-polyfill is supposed to preserve ratio, but I could never get it to work completely when stretching the browser in certain ways (operator error, I'm sure :-) ). To solve this problem, I wrote a jquery script that I've tested on safari, chrome, ff and ie8+. You'll notice that you will have to use an img positioned absolutely instead of css background-image. Just add the bgImg as an id in the tag in html.
CSS:
.container { height: auto; overflow:hidden; position:relative;}
.container #bgImg { position:absolute; z-index:-1;}
You're image selector will have to be positioned absolutely to get it to sit behind the content. That means that you're parent container has to have position: relative and then overflow: hidden so that whatever overflows from the image (since you're maintaining ratio, some pieces of it inevitable will) is hidden. Be aware also that certain display tags in the parent container will break the hiding of the overflow.
JQUERY:
$(window).load(function () {
// only do this once and pass as function parameters, because chrome
// and safari have trouble not only with document.ready but window.resize
var img = new Image();
img.src = $("#bgImg").attr('src');
var $width_orig = img.width;
var $height_orig = img.height;
resizeBGImage($width_orig, $height_orig);
$(window).resize(function () {
resizeBGImage($width_orig, $height_orig);
});
});
function resizeBGImage($width_img_orig, $height_img_orig) {
// get dimensions of container
var $width_container = $('.container').outerWidth();
var $height_container = $('.container').outerHeight();
// calculate original aspect ratio and ratio of the container
var $imageratio = $width_img_orig / $height_img_orig;
var $containerratio = $width_container / $height_container;
var $wdiff = $width_container - $width_img_orig;
var $hdiff = $height_container - $height_img_orig;
// original size, so just set to original
if (($wdiff == 0) && ($hdiff == 0)) {
$("#bgImg").css('width', $width_img_orig);
$("#bgImg").css('height', $height_img_orig);
}
// if container is smaller along both dimensions than the original image,
// set image to container size
else if (($wdiff < 0) && ($hdiff < 0)) {
$("#bgImg").css('width', $width_img_orig);
$("#bgImg").css('height', $height_img_orig+1); // adding one because chrome can't do math
}
// if container is wider than long relatiave to original image aspect ratio
// set width to container width and calculate height
else if ($containerratio > $imageratio) {
$("#bgImg").css('width', $width_container);
// calculate height using orig aspect ratio and assign to image height
$("#bgImg").css('height', (($width_container * $height_img_orig) / $width_img_orig) + 1); // adding one because chrome can't do math
}
// else container is taller than long relatiave to original image aspect ratio
// set height to container height and calculate width
else {
// set the image height to container height
$("#bgImg").css('height', $height_container + 1); // adding one because chrome can't do math
// calculate width using orig aspect ratio and assign to image width
$("#bgImg").css('width', (($height_container * $width_img_orig) / $height_img_orig));
}
$("#bgImg").css('left', (($width_container - $("#bgImg").width()) / 2).toString() + 'px');
};
Note the use of $(window).load() instead of $(document).ready(). Chrome and safari seem to have issues with the latter since in those browsers, the background image may not be fully loaded when the DOM is. Using $(window).load() ensures all window elements are in place before the script runs.
Sounds like you need a 'shim' or 'polyfill' like Modernizer:
http://modernizr.com/docs/#html5inie