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

时间:2016-03-16 12:18:04

标签: html css

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

没有路线的css设置

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

}

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

}

3 个答案:

答案 0 :(得分:2)

我不完全确定您要尝试实现的目标,但这是在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
}

答案 1 :(得分:0)

你可以使用类似的东西:

#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>

答案 2 :(得分:0)

根据您的浏览器支持要求,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>

相关问题