1

Today I visited a job interview and was asked the following question:

How can you center an image of unknown height and width both vertically and horizontally without the usage of tables (e.g. display:table-cell)?

I was given a hint that this is possible to do using before and after pseudo elements but I failed to find a solution. Could you please guys help?

idmean
  • 14,540
  • 9
  • 54
  • 83
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488

1 Answers1

1

Probably the simplest way:

DEMO

img {
    position: relative;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
}
Turnip
  • 35,836
  • 15
  • 89
  • 111
  • 1
    Ha, very good one! So `translateX` just moves the element up, correct? And the difference between say negative margin is that there is no need to specify length in px, correct? Here `translate(-50%)` `-50%` mean 50% of the elements height? – Max Koretskyi Jul 28 '14 at 14:58
  • `translateX` moves along the X axis (left to right) `translateY` along the Y axis (top to bottom). – Turnip Jul 28 '14 at 15:09
  • yeah, but I could move the element up too with negative top margin, right? However, without knowing the height of the centered box I can't specify the value for the margin, whereas with `translateX` I don't need to know the height and can say `-50%` (of the centered elements height). – Max Koretskyi Jul 28 '14 at 15:12
  • 1
    Yep. Makes things much easier – Turnip Jul 28 '14 at 15:23