将文字放在图片的左上方,并在顶部和左侧偏移百分比

时间:2019-01-09 15:53:02

标签: html css

我有以下代码,想将文本#top-left放在图像的左上方,相对于图像的父级偏移20%:div #container 。相反,发生的是文本相对于正文偏移了20%。我该如何解决?也许,我将如何使文本占图像高度的10%?

#container {
    position: relative;
}

#top-left {
    color: green;
    position: absolute;
    top: 20%;
    left: 20%;
    font-size: 5pt;
}

#img {
    width: 20%;
    height: auto;
}
<div id="container">
    <div id="top-left">Vincent Van Gogh - Wheatfield with Crows</div>
    <img id="img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Vincent_van_Gogh_%281853-1890%29_-_Wheat_Field_with_Crows_%281890%29.jpg/320px-Vincent_van_Gogh_%281853-1890%29_-_Wheat_Field_with_Crows_%281890%29.jpg" alt="Vincent Van Gogh - Wheatfield with Crows"/>
</div>

1 个答案:

答案 0 :(得分:2)

您需要先将容器收缩包装到图片的大小。

您可以使用任何适当类型的display方法,inline-block / inline-flex / inline-grid等。或使用float:left将容器缩小到图片大小。

#container {
   position: relative;
   display: inline-block;
}

#top-left {
   position: absolute;
   top: 20%;
   left: 20%;
   color: White;
}
<div id="container">
   <div id="top-left">Vincent Van Gogh - Wheatfield with Crows</div>
   <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Vincent_van_Gogh_%281853-1890%29_-_Wheat_Field_with_Crows_%281890%29.jpg/320px-Vincent_van_Gogh_%281853-1890%29_-_Wheat_Field_with_Crows_%281890%29.jpg" alt="Vincent Van Gogh - Wheatfield with Crows"/>
</div>