![](/img/trans.png)
[英]How to center align a small image with text in the center both horizontal and vertically?
[英]Align image to the center both vertically and horizontally
我有一張需要垂直和水平對齊的圖像列表。 如何使用jquery在水平和垂直方向上將圖像分別對齊在其li
的中心?
在codepen.io上演示。
的HTML:
<ul id="snap-list">
<li class="snap">
<img src="http://placehold.it/350x150">
</li>
<li class="snap">
<img src="http://placehold.it/250x350">
</li>
...
...
...
<li class="snap">
<img src="http://placehold.it/350x250">
</li>
<span class="clear_both"></span>
</ul>
CSS:
#snap-list {
list-style-type: none;
width: 100%;
}
#snap-list .snap {
width: 202px;
height: 202px;
float: left;
margin: 5px;
outline: 1px solid lightgray;
}
#snap-list .snap img {
max-width: 100%;
max-height: 100%;
}
您不需要jQuery即可執行此跨瀏覽器。
http://codepen.io/anon/pen/PZqdbV
我所做的就是添加相對於.snap的位置,並使用絕對位置將圖像居中。
* {
margin: 0;
padding: 0;
}
.clear_both {
display: block;
clear: both;
}
#main_content {
width: 850px;
margin: 0 auto;
}
#snap-list {
list-style-type: none;
width: 100%;
}
#snap-list .snap {
width: 202px;
height: 202px;
float: left;
margin: 5px;
outline: 1px solid lightgray;
position: relative;
}
#snap-list .snap img {
max-width: 100%;
max-height: 100%;
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
margin: auto;
}
如果您真的想使用jQuery,只需遍歷列表項,將它們的位置設置為相對,然后相應地定位圖像,但是使用jQuery確實沒有必要。
實際上,您將不得不等待每個圖像完全加載,否則您將無法獲得圖像的width
和height
。
因此,最好像relseanp建議的那樣使用CSS解決方案。
這是一個例子。
var listItems = $('#snap-list').find('li'); $(window).load(function() { listItems.each(function(i, item) { var crntImg = $(item).find('img'); $(item).css('position', 'relative'); crntImg.css({ position: 'absolute', top: ($(item).height() / 2) - (crntImg.height() / 2), left: ($(item).width() / 2) - (crntImg.width() / 2) }); }) });
* { margin: 0; padding: 0; } .clear_both { display: block; clear: both; } #main_content { width: 850px; margin: 0 auto; } #snap-list { list-style-type: none; width: 100%; } #snap-list .snap { width: 202px; height: 202px; float: left; margin: 5px; outline: 1px solid lightgray; } #snap-list .snap img { max-width: 100%; max-height: 100%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div id="main_content"> <ul id="snap-list"> <li class="snap"> <img src="http://placehold.it/350x150"> </li> <li class="snap"> <img src="http://placehold.it/250x350"> </li> <li class="snap"> <img src="http://placehold.it/350x350"> </li> <li class="snap"> <img src="http://placehold.it/350x450"> </li> <li class="snap"> <img src="http://placehold.it/350x250"> </li> <span class="clear_both"></span> </ul> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.