【问题标题】:Is it possible to anchor an element to a centered element?是否可以将元素锚定到居中元素?
【发布时间】:2017-07-09 10:05:48
【问题描述】:

是否可以将文本区域锚定到位于页面中间的图像上,这样当屏幕尺寸发生变化时它就不会移出图像?

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>

【问题讨论】:

    标签: html css centering


    【解决方案1】:

    .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

    【讨论】:

    • 哇,谢谢你的解释,我真的很喜欢这个解决方案和它的外观。
    【解决方案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;
    }
    

    【讨论】:

    • 我试过了,但是如果你增加屏幕尺寸,它就不再是我指定的地方了。
    • 是的,你说得对。也有必要在图像中使用绝对位置。 #cat{位置:绝对;顶部:0px;左:0px;}
    猜你喜欢
    • 2012-11-19
    • 2011-11-27
    • 2017-03-26
    • 2013-07-25
    • 2015-08-05
    • 1970-01-01
    • 2013-05-21
    • 2020-12-18
    • 2016-07-21
    相关资源
    最近更新 更多