[英]How to center an image both vertically and horizontally in a div
如何將圖像的位置設置為div的中心(垂直和水平方向)。 我可以使其水平居中,但是如何使其垂直居中?
注意:圖像的高度和寬度可能會改變。
的HTML:
{% for photo in photos %}
<div class="thumbnail_container">
<a class='gallery' href='{{MEDIA_URL}}{{photo.image}}'><img src="{{MEDIA_URL}}{{photo.image}}" class="thumbnail"></a>
</div>
{% endfor %}
<span class="clear_left"></span>
CSS:
.thumbnail_container {
background-color: white;
border: 1px solid red;
width: 250px;
height: 200px;
float: left;
margin: 5px;
}
.thumbnail {
display: block;
margin-left: auto;
margin-right: auto;
border: 1px solid red;
max-width: 240px;
max-height: 190px;
}
任何幫助都感激不盡! 謝謝。
嘗試使父容器CSS像這樣:
display:table-cell;
vertical-align:middle;
試試這個課程:
.thumbnail_container{
width: 250px;
height: 200px;
border:1px solid;
padding: 0px;
margin-bottom: 0px;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.thumbnail_container
{
border:2px solid red;
height:400px;
width:500px;
text-align:center;
}
a img
{
margin-top:15%;
}
使用可以使用transform來完成此技巧,它將始終處於中心位置
.thumbnail_container {
position: relative;
width: 200px;
height: 200px;
border: 1px solid #444;
}
.thumbnail {
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
編輯:
將此作為回退添加到單獨的CSS文件中,以定位要支持它的IE。
.thumbnail {
position: absolute;
top: 50%;
left: 50%;
width: 80px;
height: 80px;
margin-left: -40px; /* 80px/2 */
margin-top: -40px;
}
您可以通過這種方式在html文件中定位IE,然后在ie.css中添加CSS。
<!--[if lt IE 9]>
<link rel="stylesheet" href="ie.css">
<![endif]-->
因此ie.css可以在除ie9之外的任何瀏覽器上運行,因此我們可以以主要樣式對現代瀏覽器使用“翻譯”,但仍支持舊版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.