如何在不使用经典的 top:50% left:50% transform: translate(-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;
来获得良好效果。
CSS:
#container {
width: 250px;
max-height: 250px;
height: 250px;
position: relative;
display: flex;
justify-content: center;
align-items: center;
background-color: lightblue;
}
#myImage {
//removed
}
关于html - 在宽度/高度未知的元素上没有左上角变换的垂直/水平对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36035486/