Criss Criss - 1 month ago 13
CSS Question

Place img relatively to text responsively

I have h1 centered in div by

text-align: center;
line-height: 150px;
vertical-align: top;


And now I want to place img for example in left-top corner of the text. Ofc I want it not to move when the window is changing sizes. It has to always be at the corner of text.

I tried setting
position: absolute / fixed
to img and then manipulate with
top
and
left
percent values, but the img is changing position relatively to the text (h1) when I change window sizes.

I'm very new to CSS (also HTML) and I see I don't understand what is happening on the screen and don't have an idea how to solve this problem..



.container {
margin: auto;
}
.logo {
height: 150px;
text-align: center;
line-height: 150px;
vertical-align: top;
font-size: 50px;
background-image: url(../img/forest.jpeg);
background-position: 30% 20%;
}
.logo h1 {
font-family: Coiny-Regular;
color: skyblue;
}
.logo img {
position: fixed;
height: 2.5em;
top: 7%;
left: 30%;
}

<div class="container">
<div class="logo">
<h1> Example </h1>
<img src="img/image.png" />
</div>
</div>




Answer

The img:

  • use position: absolute
  • place it inside the h1

The h1:

  • make it display: inline-block;
  • have position: relative (will make the img's absolute position relative to the h1)

The display: inline-block; on the h1 will make its bounding box match its content and make it possible for the image's absolute position to stay at an exact place.

.container {
  margin: auto;
}
.logo {
  height: 150px;
  text-align: center;
  line-height: 150px;
  vertical-align: top;
  font-size: 50px;
  background-image: url(../img/forest.jpeg);
  background-position: 30% 20%;
}
.logo h1 {
  font-family: Coiny-Regular;
  color: skyblue;
  position: relative;
  display: inline-block;
}
.logo img {
  position: absolute;
  top: 0;
  left: 70px;
}
<div class="container">
  <div class="logo">
    <h1> Example
      <img src="http://placehold.it/50" />
    </h1>
  </div>
</div>