ctn should be a fixed siz...">

How to create image center in div?

My HTML code looks like this:

<div class="ctn"> <img src="some-img.jpg"/> </div> 

ctn should be a fixed size, e.g. 150 * 150.

But the IMG size can be larger or smaller: 200 * 50, 50 * 200, 50 * 50, etc.

How to make the image fit in the center of the div ? The proportion of the image should not be changed.

==== ==== UPDATE Yes, I need both a chori and a vertical center.

+4
source share
8 answers

You can add css to center the image both horizontally and vertically:

 DIV.ctn { min-height: 150px; min-width: 150px; margin-left: auto; margin-right: auto; text-align: center; display: table-cell; vertical-align: middle } 

...

 <div class="ctn"> <img src="some-img.jpg"/> </div> 

Edit: for details see: http://www.w3.org/Style/Examples/007/center.html

+15
source

Try the following:

 text-align: center; display: table-cell; vertical-align: middle; 

Demo

+4
source

I think this is your answer

 .container img { width: 100%;} .container {display: table-cell;vertical-align: middle} 

http://jsfiddle.net/RUQAM/1/

it fits in the center of your fixed size div , and the image proportions are not changed.

+2
source

EDIT: re-read, you want the image size to be fixed.

 div.cnt { margin-left: auto; margin-right: auto; text-align: center; display: table-cell; vertical-align: middle; min-height: 150px; min-width: 150px; } 
+1
source

The easiest way:

 div.cnt { width: 150px; height: 150px; } <div class="ctn" style="background: url('some-img.jpg') 50% 50% no-repeat;"> </div> 
0
source

If ctn should be a fixed size (for example: 150x150) and the image should be proportional and no larger than a div, this is the solution:

CSS

 .ctn{ background-color:#F00; margin-left:auto; margin-right:auto; position:relative; overflow:hidden; height:150px; width:150px; } .ctn div{ display:table-cell; vertical-align: middle; text-align:center; } .ctn div img{ width:150px; } 

HTML

 <div class="ctn"> <div> <img src="url" /> </div> </div> 

This method will center the div in the middle of the screen and the image will not be larger than 150x150, but it will maintain its proportionality.

0
source

Give an identifier to your like then in your css →

 #foto{ margin-left:180px; } 
0
source

set style = "margin-let: auto; margin: right: auto"

also indicate the width of the image otherwise it will not work

-4
source

Source: https://habr.com/ru/post/1483384/


All Articles