Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centre an image within a div when filling 100% width and height

Tags:

html

css

image

I am trying to centre an img within a containing div, where the img fills (minimum) 100% of the width and height of that containing div, meaning thta the image automatically scales to maintain image ratio. It is easy for me to align that img to the top, bottom, left or right, but I am hoping to centre the img both vertically and horizontally. I have been unable to locate the solution thus far, so any help greatly appreciated.

HTML

<section id="hero-image">
    <img src="https://s-media-cache-ak0.pinimg.com/originals/ae/1d/6e/ae1d6ef744320d237a95fc1e7d6ee98b.jpg">
</section>

CSS

#hero-image {
    position: relative;
    width: 100%;
    height: 400px;
    overflow: hidden;
    background: red;
}

#hero-image img {
    position: absolute;
    min-height: 100%;
    height: auto;
    min-width: 100%;
    width: auto;
    margin: auto;
    right: 0;
    left: 0;
    top: 0;
    z-index: 0;
}

Fiddle

like image 606
dungey_140 Avatar asked Jan 08 '23 07:01

dungey_140


2 Answers

Use transform:translateX(-50) to manage this (but CSS3), large screen or small screen the image will always stay center and keep his ratio aspect.

Here the fiddle

Otherwise if you want something more cross browser you will probably need a bit of javascript, but I may be wrong.

like image 192
Allan Raquin Avatar answered Apr 09 '23 15:04

Allan Raquin


Could you not set the hero image as a background? This will allow for more flexibilty both in terms of positioning and image size.

<section class="hero-image" style="background-image:url('https://s-media-cache-ak0.pinimg.com/originals/ae/1d/6e/ae1d6ef744320d237a95fc1e7d6ee98b.jpg');">
</section>

.hero-image {
    width: 100%;
    height: 400px;
    background-repeat: no-repeat;
    background-position: 50% 50%;
    background-size: cover;
}

This achieves what you've set out to do exactly. There's other benefits to this method too, for instance, responsive images.

The CSS above sets the properties for any background image within a div class of hero-image. All you need to do then, is inline the background-image itself.

NOTE: If this doesn't have to be CMS driven, you can simply apply the image to the class rather than have it inline.

like image 45
Matthew Trow Avatar answered Apr 09 '23 17:04

Matthew Trow