jquery - 将图像垂直和水平对齐到中心

标签 jquery html css

我有一个图像列表,我需要在垂直和水平方向上居中对齐。如何使用 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 - 将图像垂直和水平对齐到中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34209061/

相关文章:

jquery - 我似乎无法让 jQuery 工作

jquery - 从所有具有 class 的元素中获取 id 和 text 并将其放入 JSON 数组中

python - lxml xpath 不工作

javascript - Jquery 试图找到特定的父 div

jquery - 非CSS时如何使用JQuery检索和设置body属性

jquery - 图片导入YouTube视频

javascript - 如何突出显示按键事件后的文本?

html - Div 的内部 Bootstrap 列在缩放后重叠

html - 显示主页标题图像的新文档对话框

css - Font-Awesome 使用 CSS Pseudo After 显示正方形而不是图标