开发者

Completely center an image using CSS?

I know this is a noob-ish question but is it possible to fully center an image to the absolute center of a webpage no matter how much the page/window is changed using CSS? I'm working with a simple tag and I need to know how to? I've been looking around Google but I'm not getting a开发者_Python百科ny relevant results, probably due to my lack of correct phrasing...

I need it centred both horizontally and vertically.

Thanks!


To centre elements:

.className {
    width:200px; /*Set to image width*/
    height:100px; /*Set to image height*/
    position:absolute; 
    top:50%; 
    left:50%; 
    margin:-50px auto auto -100px; /*Half of image width, 0, 0, half of image height*/
    text-align:center;
}

HTML:

<img src="whatever.jpg" class="className" />

JSFiddle:

http://jsfiddle.net/Mutant_Tractor/xBRq9/


A. To center a background (it usually is a good idea to center images like this):

background-image: url(your/image.ext);
background-repeat: no-repeat;
background-position: center;

B. Inline elements (span, img, a) can be centered horizontally by setting text-align: center; on the parent.

C. HTML block elements can be centered horizontally with

margin-left: auto;
margin-right: auto;

Centering vertically is a bit more complex.


I solved it this way:

img.class-name{

    position: absolute;
    margin: auto;
    left: 0; 
    right: 0;
    top: 0;
    bottom: 0;  
}


DEMO

You need to make a div and position it with

text-align:centre;

and then you can centre your image vertically within the div like in the fiddle


If you want to center image to the center regardless of screen size, you can try out this code

img{
   display: flex;
   justify-content:center;
   align-items: center;
   height: 100vh;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜