Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How center an absolute element (img) that's wider than its parent div?

I'm trying to center an absolute positioned img inside a relative positioned div and the image is bigger than its parent(in a 767px window or lower). But the image does have a fixed width of 767px. What makes it hard for me is that parent div does not have a fixed width, it has a 100% width so I'd have to somehow generate the correct amount of pixels for the 'left' attribute on each resize but I don't know how. I tried setting percentages but with no succes when resizing.

I have been able to somewhat do it with javascript but I'd rather have a css solution since the javascript doesn't work consistently for me.

I need to be able to center the img when the parent div gets smaller than 767px and the img always remains 767px within the div and has a height of 257px.

Any help is appreciated!

html code:

<div class="item">
  <img src="...">
</div>

css:

.item{
position:relative;
height:257px;
overflow:hidden;
}

.item img{
min-width:767px;
position:absolute;
}
like image 937
Noob17 Avatar asked Jul 25 '15 02:07

Noob17


1 Answers

A way of doing this without having to hard-code half the width.

For instance, maybe your child element has a variable width that you cannot predict

You can do this instead:

left: 50%;
transform: translateX(-50%);
like image 91
Jack Avatar answered Oct 31 '22 16:10

Jack