techfoobar
techfoobar

Reputation: 66693

Horizontally centering a child element inside a parent narrower than the child element

I've been trying to horizontally center a wide <img> element inside a <div> which is not as wide as the image itself. And the <div> has overflow: hidden set on it.

For instance, the image is 500px wide and the DIV is 250px wide. Is there any clean way (such that it works for images of any dimension) to center the image such that only the center portion shows up inside the div.

Upvotes: 2

Views: 120

Answers (3)

Praveen
Praveen

Reputation: 56509

Since you're expecting a responsive behavior, I would suggest to have (for a simple one)

div {
 text-align: center;
}

But using CSS3 and media queries it is possible.

Check this out How to Create a Responsive Centered Image in CSS3

Quick demo

Upvotes: 0

Jignesh Kheni
Jignesh Kheni

Reputation: 1312

you can add your image as a background using css and give background position to center center.

Upvotes: 0

Virus721
Virus721

Reputation: 8335

<div class="Container">
    <img class="Thumb">
</div>

And :

.Container {
    position: /* anything but static */
    width: 250px;
}

.Thumb {
    position: relative;
    width: 500px;
    margin: 0 auto;
}

Upvotes: 2

Related Questions