我无法成功将div的中心放在“ img”类中,而div包含在类“ sign”中的img上。
.container{
width: 500px;
height: 300px;
position: relative;
}
img{
width: 100%;
height: auto;
}
.sign{
width: 90%;
background-color: brown;
padding: 2px;
position: absolute;
bottom: 10%;
text-align:center;
}
.sign h1{
color: black;
}
<div class="container">
<img src="https://st3.idealista.com/news/archivos/styles/news_detail/public/2019-08/casa_malaga_fachada.jpg?sv=_n3BRi9v&itok=5LkoQoXO" />
<div class="sign">
<h1>House on sale</h1>
</div>
</div>
您可以使用容器上的display: flex
和justify-content: center
来实现这一点>
.container { display: flex; justify-content: center; width: 500px; height: 300px; position: relative; } img { width: 100%; height: auto; } .sign { width: 90%; background-color: brown; padding: 2px; position: absolute; bottom: 10%; text-align: center; } .sign h1 { color: black; }
<div class="container"> <img src="https://st3.idealista.com/news/archivos/styles/news_detail/public/2019-08/casa_malaga_fachada.jpg?sv=_n3BRi9v&itok=5LkoQoXO" /> <div class="sign"> <h1>House on sale</h1> </div> </div>
如果您想继续使用display: absolute
,则可以将以下内容添加到.sign { ... }
.sign {
position: absolute;
bottom: 10%;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
}