垂直/水平对齐,在具有未知宽度/高度的元素上没有左上角变换



如何在不使用经典顶部的情况下将该项目与自动生成的宽度/高度垂直/水平对齐 顶部:50% 左:50% 变换:平移(-50%,-50%)

没有对齐方式的 CSS 设置

#container {
width: 200px;
height: 100px;
background-color: lightblue;

}

#myImage {
width: auto;
height: auto;
max-height: 100px;
max-width: 200px;

}

我不完全确定您要实现的目标,但这是在CSS中没有设置固定高度或宽度的图像。我假设从您的 OP 中您想要的是这样的居中 - 因此,如果图像尺寸发生变化,它将沿两个轴保持居中。

请注意,您面临的唯一限制是那些不支持 flex 的旧版浏览器。如果这是一个问题,您可以使用display: table;display: table-cell;来获得良好的效果。

http://jsfiddle.net/dLLan/29/

.css:

#container {
 width: 250px;
 max-height: 250px;
 height: 250px;
 position: relative;
 display: flex;
 justify-content: center;
 align-items: center;
 background-color: lightblue;
 }
#myImage {
 //removed
}

你可以使用这样的东西:

#helper {
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}
#container {
  width: 200px;
  height: 100px;
  background-color: lightblue;
  text-align:center;
}
#myImage {
  width: auto;
  height: auto;
  max-height: 100px;
  max-width: 200px;
  vertical-align: middle;
}
<div id="container">
  <div id="helper"></div>
  <img id="myImage" src="http://s3.amazonaws.com/hirethings/photo/7250/images/thumbnail.jpg?1274508483" />
</div>
根据您的

浏览器支持要求,Flexbox在这里应该没问题。

无需

定位图像...Flex 会做到这一点。

.container {
  width: 200px;
  height: 100px;
  background-color: lightblue;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 1em;
}
.large {
  width: 300px;
  height: 200px;
}
.myImage {
  width: auto;
  height: auto;
}
<div class='container'>
  <img class='myImage' src='http://s3.amazonaws.com/hirethings/photo/7250/images/thumbnail.jpg?1274508483' />
</div>
<div class='container large'>
  <img class='myImage' src='http://lorempixel.com/image_output/food-q-c-250-160-5.jpg' />
</div>

最新更新