我在边距、位置等方面玩了很多,但如果不粗略地手动输入位置,我就无法将文本居中放置在我想要的位置,即 left: 10px;
。这可能很简单,但我作为一个学习者无法理解
.container {
position: relative;
}
.text-block-main {
position: absolute;
bottom: 5%;
right: 44%;
background-color: black;
opacity: 75%;
color: white;
padding-left: 20px;
padding-right: 20px;
border-radius: 15px;
border: 2px solid white;
padding: 10px;
}
<div class="container">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg/1200px-Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg" alt="vvg" style="height:100%;" class="center">
<div class="text-block-main">
<h2> The Starry Night </h2>
<h3> Vincent van Gogh </h3>
</div>
</div>
它有点居中(手动),但不是真的居中,取决于我使用的图像本身,所以我必须为我想使用的每个图像调整它。感谢对此的一些帮助
最佳答案
使用 flex
的解决方案。在container
类上指定display: inline-flex
,采用img
标签图片的形式。
同时从 text-block-main
类中删除 bottom
和 right
。
我在 css 中标记了所有的编辑。
.container {
position: relative;
display: inline-flex; /*add this it*/
align-items: center; /*add this it*/
justify-content: center; /*add this it*/
}
.text-block-main {
position: absolute;
/*bottom: 5%;*/ /*remove this it*/
/*right: 44%;*/ /*remove this it*/
background-color: black;
opacity: 75%;
color: white;
padding-left: 20px;
padding-right: 20px;
border-radius: 15px;
border: 2px solid white;
padding: 10px;
}
<div class="container">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg/1200px-Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg" alt="vvg" style="height:100%;" class="center">
<div class="text-block-main">
<h2> The Starry Night </h2>
<h3> Vincent van Gogh </h3>
</div>
</div>
关于html - 如何在已经居中的图像上叠加文本中心底部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64909579/