Reputation: 35
I'm trying to center an image vertically within its container so that when the browser width changes and the image grows to max-width of 1500px the image is cropped equally on both the top and bottom. The image has a max-height of 450px no matter the width. I'm not sure it this explanation makes sense.
Here is my CSS code:
<style>
.Center-Container {
position: relative;
background-color: #ccc;
height: 450px;
width: 100%;
max-width: 1500px;
}
.Absolute-Center {
width: 100%;
height: 450px;
overflow: hidden;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
}
img {
max-width: 100%;
}
</style>
Here is the HTML code:
<div class="Center-Container">
<div class="Absolute-Center">
<img src="images/coverimage.jpg" />
</div>
</div>
You can view the site here: http://www.concept82.com/center/testcenter.html. Please excuse the current image; I'm using it as a placeholder for the moment. Thanks so much for your time...I'm still a beginner at this!
Upvotes: 1
Views: 76
Reputation: 18932
It is possible to vertically center an img element. This is a great resource: How to crop an image with a CSS class
To vertically center using percentages:
CSS
.image-cropper {
position: relative;
width: 360px;
height: 240px;
overflow: hidden;
border: 1px red solid;
}
.centered {
position: absolute;
left: -50%;
top: -50%;
}
HTML
<div class="example">
<p>Center cropped image</p>
<div class="image-cropper">
<img class="centered" alt="myimage" src="images/myimage.jpg" />
</div>
</div>
Upvotes: 0
Reputation: 13853
You can't easily crop a content image. Try making the image a background image through CSS and using background-size: cover:
:
#image {
background: #D84E51 url(http://placekitten.com/800/800?image=10) no-repeat center center;
width: 400px;
background-size: cover;
}
Examples on Codepen: http://codepen.io/KatieK2/pen/KaigG
Also add some media queries to handle different styling for different viewport widths.
Upvotes: 1