Centering an object of unknown width in a container of unknown width
I have a design problem when I try to center a wide image relative to the container. The problem is that the width of the image is unknown, so I can't seem to do the trick left:50%, margin-left:-###px;
because I don't know what that negative value is.
I also can't use text-align:center;
it because the image is bigger than the container.
To complicate matters, the width of the container is also unknown.
I would really like to avoid using JavaScript to do this, but that seems like a big question using CSS
.
Does anyone know of any magic solution here?
UPDATE:
Required support: IE8 +, Chrome, Safari, Firefox, Android.
I tried a couple of examples provided by the lovely people you provided that didn't work (they will work in most situations, but not mine).
@Vince - I tried your block-screen trick, which works great when the window is larger than the image, but when the window is not wider than the image, it effectively becomes "left-aligned".
See example script. I added another container to simulate a narrow mobile window. Obviously it won't be hard-coded width like in fiddle. Also, the img width will not be hardcoded as in the example, but I am trying to simulate the situation presented to me.
http://jsfiddle.net/7n1bhzps/1/
Sorry for the disgusting colors.
UPDATE 2:
The accepted answer is dfsq. Contrary to the above, it doesn't need IE8 support as the issue is with mobile permissions. IE8 is not a mobile browser, so no support is required.
Thanks everyone.
source to share
You can use CSS transofrm: translateX(-50%)
to move an image of unknown width. This technique allows you to center an image of any width relative to the container.
.wrap {
margin: 0 0 10px 160px;
width: 300px;
height: 75px;
border: 3px red solid;
position: relative;
overflow: hidden;
}
.wrap:hover {
overflow: inherit;
}
.wrap img {
position: absolute;
left: 50%;
-ms-transform: translateX(-50%);
-webkit-transform: translateX(-50%);
transform: translateX(-50%);
}
<div class="wrap">
<img src="http://lorempixel.com/600/75/food/3" alt="">
</div>
<div class="wrap">
<img src="http://lorempixel.com/100/75/food/4" alt="">
</div>
Check support http://caniuse.com/#feat=transforms2d
source to share
Set the minimum width of the container to whatever you see fit. Set the image to be displayed as a block and use a trick margin: 0 auto;
to center it
HTML:
<div id="contain">
<img src="http://i.imgur.com/xs8vh.jpg"/>
</div>
CSS
#contain {
min-width: 50px;
}
#contain img {
display: block;
margin: 0 auto;
}
JSFiddle: http://jsfiddle.net/j21a8ubo/
source to share
Centering sometimes doesn't work, but it can also be a browser related issue.
If you can customize the HTML, you can position the element in the center of the cell in an element <table>
with a cell on either side of it. This has been done in IE8 and earlier, although it is now deprecated.
source to share