固定尺寸容器內,圖片尺寸不固定,需水平垂直置中顯示。
.container {
display: flex;
justify-content: center; /* 水平置中 */
align-items: center; /* 垂直置中 */
width: 300px; height: 200px;
border: 1px solid #ccc;
}
.container img { max-width: 100%; max-height: 100%; }
.container {
display: grid;
place-items: center; /* 等同 justify-items:center + align-items:center */
width: 300px; height: 200px;
}
.container {
position: relative;
width: 300px; height: 200px;
}
.container img {
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
max-width: 100%; max-height: 100%;
}
.container {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 300px; height: 200px;
}
.container img { vertical-align: middle; max-width: 100%; max-height: 100%; }
需在外層再包一個 display:table 容器才在 IE8 生效。
.container {
text-align: center;
height: 200px;
}
.container::before {
content: ""; display: inline-block;
height: 100%; vertical-align: middle;
}
.container img { vertical-align: middle; max-width: 100%; max-height: 100%; }
