【问题标题】:Giving a div a width and a height aligns it left给 div 一个宽度和一个高度使其左对齐
【发布时间】:2021-07-30 14:32:12
【问题描述】:

所以主要问题是,当我有一个包含图像列表的 div 并且我想将其放入幻灯片库并为其指定宽度和高度时,它将始终在左侧对齐。

所以,这是我的 .html 代码:

.touchgallery {
  position: relative;
  overflow: hidden;
  width: 800px;
  /* default gallery width */
  height: 600px;
  /* default gallery height */
  background: #eee;
}

.touchgallery ul {
  list-style: none;
  margin: 0;
  padding: 0;
  left: 0;
  position: absolute;
  -moz-transition: all 100ms ease-in-out;
  /* image transition. Change 100ms to desired transition duration */
  -webkit-transition: all 100ms ease-in-out;
  transition: all 100ms ease-in-out;
}

.touchgallery ul li {
  float: left;
  display: block;
  width: 800px;
  text-align: center;
}

.touchgallery ul li img {
  /* CSS for images within gallery */
  width: 95%;
  max-width: 1000px;
  height: auto;
}
<div id="swipegallery" class="touchgallery">
  <ul>
    <li>
      <img src="https://picsum.photos/200/200">
    </li>
    <li>
      <img src="https://picsum.photos/200/200">
    </li>
    <li>
      <img src="https://picsum.photos/200/200">
    </li>
    <li>
      <img src="https://picsum.photos/200/200">
    </li>
  </ul>
</div>

如果我从 .touchgallery 中删除宽度和高度参数,它将居中对齐(可能是因为我写了正文始终居中)。但是一旦我再次将宽度和高度设置为同时只显示一个图像而不是一次全部显示,图像将自动在左侧对齐,我无能为力。

所以我的问题是:

  1. 如何使 div 居中?
  2. 为什么width和height参数会导致div左对齐?

【问题讨论】:

  • 您是否尝试过使用margin: auto 使 div 居中?
  • 我关闭了一个未关闭的&lt;div&gt; 并添加了一些图片。尝试运行 sn-p 我认为它不会重现您所描述的内容

标签: html css


【解决方案1】:

要使 div 居中,您需要使用

margin: auto;

在 .touch-gallery 上。

我猜测图像向左对齐,因为在 .touch-gallery ul li 中,您告诉它始终向左浮动。

.touchgallery ul li{
    display: block;
    width: 800px;
    text-align: center;
    float: left;
}

【讨论】:

    猜你喜欢
    • 2017-10-31
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-20
    • 1970-01-01
    相关资源
    最近更新 更多