Centering an image on screen using CSS - Random Screen/Image dimensions

主宰稳场 提交于 2019-12-12 17:09:58

问题


I have to create a web page that for the purposes of this question is a single image centered both vertically and horizontally in the center of the screen. It has the following requirements:

  • The screen size of the client is unknown (mobile)
  • The image is user-defined and therefore is of unknown dimensions
  • The image must be perfectly centered both vertically and horizontally on all devices
  • The image centering must persist through a screen rotation (i.e. from portrait to landscape)

Being a bit of a CSS newb, I went and created this the only way I knew how, using javascript to position the content: http://jsfiddle.net/error454/8YL9a/

I'm looking for a solution that functions identically to my solution but uses CSS instead of hard equations.


回答1:


display:-webkit-box;
-webkit-box-orient:horizontal;
-webkit-box-pack:center;
-webkit-box-align:center;

display:-moz-box;
-moz-box-orient:horizontal;
-moz-box-pack:center;
-moz-box-align:center;

CSS3 property, bad support : webkit, mozilla. Only way to do it with clean markup and CSS without JS.

edit 1 : http://jsfiddle.net/t8qtn/6/

edit 2 : for future proofing, the prefixless version is

display:box;
box-orient:horizontal;
box-pack:center;
box-align:center;



回答2:


This is a nice article on centering: http://www.w3.org/Style/Examples/007/center.en.html

It should be something like:

.vcenter { display:table-cell; vertical-align:middle; }
.hcenter { display:block; margin-left:auto; margin-right:auto; }

And then apply both classes to your image:

<img class="vcenter hcenter" src="..."/>

Update: you could simply use a table like here http://www.sorinvasilescu.ro/



来源:https://stackoverflow.com/questions/9915971/centering-an-image-on-screen-using-css-random-screen-image-dimensions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!