0

I want an <img> tag to be exactly 100% width of the browser window when loading, but when the window is resized (down to mobile width), the image stays in the dead center of the window, remains the same size and the edges are cut off. Can you do this using just css? If so, how?

Marco Prins
  • 7,189
  • 11
  • 41
  • 76
  • 1
    Remains the same size? You mean as it is on a desktop size screen? – putvande Jun 23 '14 at 15:22
  • Yes, not be resized. So only the middle part is visible – Marco Prins Jun 23 '14 at 15:22
  • http://stackoverflow.com/questions/10830735/center-image-in-div-with-overflow-hidden – Paulie_D Jun 23 '14 at 15:32
  • 1
    @Paulie_D I don't think this is the same effect as the OP is trying to achieve, on that solution the image does not stay centered. – Andy Jun 23 '14 at 15:36
  • 1
    then perhaps this - http://stackoverflow.com/questions/1344169/center-image-in-a-div-too-small-for-it?rq=1 However it woudl make much more sense to substitute the image for a div and use the image as a bg image of that div as you suggested, – Paulie_D Jun 23 '14 at 15:37

2 Answers2

2

By far the easiest way to do this is to set a div with a background-image and background-position: center, this will achieve the desired effect.

div {
    background: url([imageurl]) no-repeat top center;
    width: 100%;
    height: [imageheight];
}

Demo

Andy
  • 4,538
  • 2
  • 26
  • 34
1

I highly recommend using background-size: cover for these sorts of occasions.

html { 
   background: url(images/bg.jpg) no-repeat center center fixed; 
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
   background-size: cover;
} 

(as taken from here)

  • 1
    But remember, this is an image tag, not a background image. It is only at the top of the page. I am already using another image (small logo with background-repeat) as my background – Marco Prins Jun 23 '14 at 15:28
  • @MarcoPrins Then replace the `` with a `
    ` which has the image as a background. You can use the background property on multiple elements
    – zgood Jun 23 '14 at 15:31
  • or use a double background image – valerio0999 Jun 23 '14 at 15:40