html - 在 3 个响应列的绝对定位中居中图像

标签 html css

我试图将一个图像(在我的 fiddle 示例中的可口可乐的“可口可乐”)居中,该图像位于没有固定宽度的绝对元素 .itemDisplay 中。

我认为没有固定宽度是个问题,因为它似乎会阻止图像居中。

有很多关于在绝对元素内居中的答案,但我找不到任何关于多列的答案,而不仅仅是左边的 50%,等等答案。 .itemDisplay 位于名为 .parentItem 的 div 中,占屏幕的 32%,带有一些填充和边距,每行 3 个。

所有 3 列都有自己的图像,但我只做了第一个作为示例。

当包含古柯图像的 div 悬停时,它当前显示一个隐藏的带有可乐的 div,图像居中,这正常工作,我唯一的问题是将古柯图像居中。

我已经尝试了所有答案,但似乎无法正常工作。

任何想法!?

https://jsfiddle.net/se23vvwu/

最佳答案

您的父元素需要是相对的并且具有其子元素的大小。为此,如果你不能有一个固定的宽度,你可以使用 width: fit-content;。 然后我应用 left: 0;和 right: 0; 为绝对元素。

这是结果(你仍然需要适应悬停状态):

#shopShelves {
width : 100%;
padding : 15px;
max-width : 100%;
margin : 0 auto;
}
.parentItem {
height : 200px;
background-color : #e7e7e7;
float : left;
margin-left : 1px;
margin-bottom : 1px;
position: relative;
}
.parentItem a {
position: relative;
width: 100%;
height: 100%;
display: inline-block;
}
.parentItem:hover .hoveredItem {
opacity : 1;
z-index : 1;
}
.parentItem:hover .itemDisplay {
opacity : 0;
}
.I33 {
width : 33.2%;
}
.displayCenter {
position : relative;
width : 33.2%;
background-color : #F00;
}
.parentItem:hover {
opacity : 1;
}
.itemDisplay {
  opacity: 1;
  transition: opacity 0s 0.2s;
  position: absolute;
  display: block;
  width: fit-content;
  left: 0;
  right: 0;
  margin: 0 auto;
}
.hoveredItem {
opacity : 0;
margin-bottom : 0;
}
.imgcenter {
display : block;
margin : auto;
max-width : 280px;
float : none;
position : relative;
}

width: fit-content; 与 IE 有一些兼容性问题。但我很确定有解决方法。有些人使用 display: table;

更多浏览器特定属性:

  width: intrinsic;           /* Safari/WebKit uses a non-standard name */
  width: -moz-max-content;    /* Firefox/Gecko */
  width: -webkit-max-content; /* Chrome */

您可能需要做更多的研究。

希望这对您有所帮助!

关于html - 在 3 个响应列的绝对定位中居中图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46161618/

相关文章:

CSS: wrap text <pre> 标签断词问题

html - 如何在html中排列标签和输入

html - :before Pseudo element behind absolute positioned parent

jquery - 使用 jquery 修改样式不同于 css

javascript - 在 HTML5 视频元素中播放电影时如何在 IOS 上显示非全尺寸视频?

javascript - 在 for 循环中使用 setTimeout

php - 在数据库搜索中排除 HTML 标签

javascript - 如何让表格不改变大小?

javascript - 如何在其父组件(DOM 层次结构)之外呈现子组件 - React.js

JavaScript/HTML 表单验证