开发者

How to center an image that is wider than the browser window (not a background image)

开发者 https://www.devze.com 2023-03-23 11:42 出处:网络
How can I centre a large image to the browser window, so that if it is wider than the window it will still be centred?

How can I centre a large image to the browser window, so that if it is wider than the window it will still be centred?

See: http://carolineelisa.com/rob/

I did not want to simply make the image a background image, as it changes dynamically to images of different sizes and I want to to be able to scroll down to see them at the correct heights.

Howev开发者_如何学Pythoner I am open to making it a background image if the height of the container div can change depending on the background image height?

I don't mind having a horizontal scrollbar, but would prefer not to.

Thanks!


<div style="background:url(/path/to/image.png) center top; width:100%; overflow:hidden">
  <img src="/path/to/image.png" style="visibility: hidden;">
</div>

This... probably will get you where you want.

and the example: fiddle and source

Edit

fixed it: fiddle and source


Nearly two years later, I was having a similar issue and wanted to solve it with only html/css (using javascript only to change between images).

Finally I had to resolve to a total of three elements to achieve always centered images (images both smaller and larger than the page/wrapping element).

The html construction

<div class="container">
    <div class="align"><img src="http://thecustomizewindows.com/wp-content/uploads/2011/11/bulb-wallpaper.jpg" /></div>
</div>

The css:

div.container
{
    position: relative;
    width: 100%;
    overflow: hidden;
}
div.container div.align
{
    position: relative;
    width: 10000px;
    left: 50%;
    margin: 0 0 0 -5000px;
    text-align: center;
}

While I don't really like having to work with insanely stretched elements, it seems super effective.

Here's the fiddle: http://jsfiddle.net/NjJ3G/3/


Best solution with an img tag of unknown dimensions is to :

.bg-fluid {
    position:absolute;
    left:-1000%;right:-1000%; // horizontal center
    top:-1000%; bottom:-1000%; // vertical center
    margin: auto;
}

you can also make it responsive with:

.bg-fluid-responsive {
    min-width: 100%;
    min-height: 100%;
}

and the img tag:

<img class="bg-fluid bg-fluid-responsive" src"..."/>

no need for containers.

note: aspect ratio will be preserved.


Honestly, the best way to do it is with a background image. Since you're going to be using javascript to change the image, you can go ahead and add a little more to change the height as well. To do so, load the image into an invisible div (style="position:absolute; top:-3000px; left:-3000px;") in addition to setting it as a background-image. You can then use javascript to get its height from the img tag inside the invisible div.

0

精彩评论

暂无评论...
验证码 换一张
取 消