css - 如何使用CSS定位不同大小的图像?

标签 css sass

我有两张宽度和高度不同的图片,需要将它们放在图片框的底部居中位置。这是 HTML 和 CSS 示例。

<div class="box">
     <div class='image'>
        <img alt="" src="image.jpg"/>
     </div>
</div>

.box {
  max-width: 970px;
  height: 440px;
}
.box img {
  max-width: 100%;
  position: absolute;
  bottom: 8px;
  margin-left: auto;
  margin-right: auto;
}

此代码适用于精确宽度和高度的大图像。但是,当将较小的图像放置在图像框中时,该图像位于右下角的中央。如何使两个图像都居中底部?

感谢大家的帮助!

最佳答案

给你...我会尽量解释,但简短的回答,a fiddle

.box {
  /* Just so I could see the parent */
  background-color: #bada55;
  max-width: 970px;
  height: 440px;
  /* Needed to make this element positional (so it will contain the absolutely positioned child */
  position: relative;
  /* Yep, center wasn't necessary here... */
}
.box .image { /* move this to the image wrapper */
  position: absolute;
  bottom: 8px;
  /* Force full width */
  left: 0;
  right: 0;
  /* Center contents (the image) */
  text-align: center;
}
img {
  max-width: 100%;
}

关于css - 如何使用CSS定位不同大小的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20110520/

相关文章:

javascript - 如果 div 包含某个单词,替换它所在的整个句子?

html - 单击选项卡时停止页面跳转

css - header 未出现在 IE 7 中...可能有什么问题?

css - 使用 Bootstrap 时将背景图像添加到 Rails 应用程序

javascript - 如何以相对方式在 React 表(父)中定位弹出框(子页面) - CSS/ReactJS/Javascript

html - 媒体查询 - 使图像响应

sass - 如何引用 map 对象内部的属性

javascript - Webpack 不会编译带有背景图像的 SASS

CSS Transition another div (SASS) and itself//编辑加载顺序问题

css - Rails application.css.scss 不知道其他正在使用的 scss 文件?