1

I've following code:

HTML

<div class="banner">
    <img src="banner.png">
</div>

CSS

.banner > img {
    margin: auto;
}

The Image have a width of 3000px and a height of 200px I want the image horizontal centered and no horizontal scroll bar. (Browser resizing should no problem then)

I've tried to give the .banner div the banner image as background-image but then the div won't find it's size automatically ...

How is this possible?

Huangism
  • 16,278
  • 7
  • 48
  • 74
fechnert
  • 1,215
  • 2
  • 12
  • 30
  • If you set a background then you can use a 30x2 transparent image and set it to width 100% so it will take up the correct amount of space for the div – Huangism Sep 03 '14 at 18:08
  • 2
    possible duplicate of [center oversized image in div](http://stackoverflow.com/questions/14562457/center-oversized-image-in-div) – Bojangles Sep 03 '14 at 18:09
  • 1
    If you need to use an ``, look at the duplicate I've marked this as. If you can use a background image, try doing [`background-size: cover`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-size) with a CSS background image – Bojangles Sep 03 '14 at 18:11
  • The answer of nicogaldo describe what i was searching, but thanks. It's also very useful! – fechnert Sep 03 '14 at 18:26

3 Answers3

3

Your best option is using the images as background, but if you want/need to use the image, do it like this

.banner{overflow:hidden; height:200px; width:100%; text-align:center;}
.banner img{width:100%; height:100%; margin:0 auto;}
Devin
  • 7,690
  • 6
  • 39
  • 54
  • I don't want to set the exact size og the image in css. Should be dynamically – fechnert Sep 03 '14 at 18:18
  • 1
    you mention fixed sizes in your post. Anyways, for that, the better way is to use the image as background as I mentioned and other people did – Devin Sep 03 '14 at 18:20
3

How to Center an Image in HTML & CSS and prevent horizontal scroll bar?

1. Prevent horizontal scroll bar:

Try this will work perfectly, add overflow-xproperty to the class and set it to hidden, That Will Disable The Horizontal Scroll Bar in CSS. See How to prevent horizontal scrolling? - Stack Overflow.

2. How to Center an Image in CSS?

You can center the image by using these CSS properties:

  1. display: flex;.
  2. justify-content: center;.

CSS code:

.banner {
    overflow-x:hidden;
    display: flex;
    justify-content: center;
}

HTML code:

<div class="banner">
    <img src="">
</div>
H3AR7B3A7
  • 4,366
  • 2
  • 14
  • 37
1
<div class="banner">
</div>

css:

.banner {
    background: url(http://ximg.es/3000x200/000/fff.png) no-repeat 50% 50%;
    height:200px;
}

like this: jsfiddle

nicogaldo
  • 565
  • 2
  • 8
  • 28