2 回答

TA貢獻1866條經驗 獲得超5個贊
首先將絕對塊放在容器中間居中,我們可以這樣做
top: 50%; left: 50%; transform: translate(-50%,-50%);
top
和 left
將根據元素的左上角定位元素,然后我們使用 Transform 根據元素自身的方向將元素在兩個方向上移動一半寬度和高度。
現在,一旦塊完全居中,我們就可以在其中添加我們想要的任何內容。
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
}
.child1 {
width: 100%;
height: 200px;
background-color: red;
}
.child2 {
width: 100%;
height: 200px;
background-color: green;
}
.main {
position: relative;
width: 100%;
}
.absolute-block {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 16%;
border: 2px solid yellow;
}
img {
max-height: 100%;
max-width: 100%;
border-radius: 50%;
border: 5px solid white;
}
<div class="main">
<div class="absolute-block">
<img src="https://i.picsum.photos/id/353/300/300.jpg">
</div>
<div class="child1"></div>
<div class="child2"></div>
</div>

TA貢獻1848條經驗 獲得超2個贊
您想嘗試以下方法嗎?
img {
width: 100%;
height: auto;
position: relative;
top: 50%;
-ms-transform: translateY(-50%);
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
}
- 2 回答
- 0 關注
- 174 瀏覽
添加回答
舉報