2

Is it possible to anchor a textarea to an image that is centered in the middle of the page, so that it doesn't move out of the image when the screen size changes?

Example on jsfiddle: https://jsfiddle.net/rxg7t2ca/1/

.container {
  width: 60%;
  margin: 0 auto;
  /* border: 2px solid blue; */
}

#cat {
  display: block;
  margin: 0 auto;
}

.box1 {
  position: relative;
  top: -250px;
  left: 30px;
  width: 100px;
  height: 100px;
}
<div class="container">
  <img src="http://i.imgur.com/a2Wd9D2.jpg" height=300px id="cat" />
  <textarea class="box1"> This is a text box </textarea>

</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Eric
  • 954
  • 2
  • 14
  • 23

2 Answers2

2

In the container use 'position:relative', and in the textarea and in the image use 'position: absolute'.

CSS absolute property: The element is positioned relative to its first positioned (not static) ancestor element.

.container{
  width: 60%;
  margin: 0 auto;
  position:relative;
  /* border: 2px solid blue; */
}

#cat{
  position: absolute;
  top: 0px;
  left: 0px;
  display: block;
  margin: 0 auto;
}

.box1{
  position: absolute;
  top: 25px;
  left: 30px;
  width: 100px;
  height: 100px;
}
Jorge Guerrero
  • 323
  • 3
  • 5
  • I've tried this but if you increase the screen size it will no longer be where i specified it. – Eric Jul 09 '17 at 01:45
  • Yes, you right. is necessary to use the position absolute in the image too. #cat{position: absolute; top: 0px; left: 0px;} – Jorge Guerrero Jul 09 '17 at 01:58
2

.container {
  position: relative;
  width: 60%;
  margin: 0 auto;
  border: 2px solid blue;
}

#cat {
  width: 100%;
  object-fit: cover;                 /* 1 */
  vertical-align: bottom;            /* 2 */
}

.box1 {
  position: absolute;                /* 3 */
  top: 50%;                          /* 3 */
  left: 50%;                         /* 3 */
  transform: translate(-50%, -50%);  /* 3 */
  width: 100px;
  height: 100px;
}
<div class="container">
  <img src="http://i.imgur.com/a2Wd9D2.jpg" height=300px id="cat" />
  <textarea class="box1"> This is a text box </textarea>
</div>

Explanations:

  1. Why isn't object-fit working in flexbox?
  2. Mystery white space underneath image tag
  3. Element will not stay centered, especially when re-sizing screen
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
  • 1
    Wow thank you for the explanations, And i really like the solution and how it looks. – Eric Jul 09 '17 at 02:27