是否可以将元素锚定到居中元素?

时间:2017-07-09 01:27:41

标签: html css centering

是否可以将textarea锚定到页面中间居中的图像,以便在屏幕尺寸发生变化时它不会移出图像?

关于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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

在容器中使用'position:relative',在textarea和图像中使用'position:absolute'。

CSS绝对属性:元素相对于其第一个定位(非静态)祖先元素定位。

.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;
}

答案 1 :(得分: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>

说明:

  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