使用Position:relative包含图片区域内的文本;

时间:2016-09-07 20:14:06

标签: javascript jquery html css position

我试图弄清楚如何使用Position:relative来保持一个对象(让它称之为文本)在屏幕上的同一个地方,无论屏幕大小如何。

当我使用Position:relative,并设置" left"例如30%......它占屏幕的30%。我试图弄清楚如何将文本放在图像上并将文本设置为图像中剩余30%。无论屏幕大小如何,我都需要这个。到目前为止,我一直无法做到。

有人可以向我解释位置相对和位置绝对在这种情况下如何运作?或者如何最好地处理这个问题?

谢谢!

这是我的JsFiddle,而这里是片段



.center {
  display: table;
  margin: 0 auto;
}
body {
  background-color: #27ae60;
}
.image {
  position: relative;
  width: 100%;
  /* for IE 6 */
}
.element {
  position: absolute;
  top: 100px;
  left: 30%;
  width: 100%;
  font-size: 45px;
  font-family: 'Just Me Again Down Here', cursive;
}
.input {
  /*color: blue;*/
  outline: none;
  border: none;
  background-color: transparent;
  position: absolute;
  top: 220px;
  left: 18%;
  width: 480px;
  height: 475px;
  overflow: hidden;
  font-size: 30px;
  font-family: 'Just Me Again Down Here', cursive;
}

<img id='image' class='center' src='https://s13.postimg.org/li2l28a0n/White_Board.gif'>


<h1 class='element'>This is a header </h1>
<textarea id='text1' class='input' placeholder="Write your answer here."></textarea>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

  1. 首先我们设置一个带.desk课程的div,桌面会收到所需的背景图片,固定的宽度和高度,因为桌子没有margin 0 auto有一个容器。

  2. .header课程不一定是绝对的,我们在已经相对定位的桌子内使用它。我们给它一点填充,以便它适合桌面图像。

  3. .answer类已应用于textarea元素,因为我们在width 100%;已经预定义宽度的.desk内使用它,这意味着.answer将在桌面上装备所有可能的宽度。

  4. 一个好的提示总是在CSS中很简单,了解position: absolute的用法,当它真的有必要时。顺便说一下,如果您不熟悉rem大小调整,我建议您在这里查看:https://www.sitepoint.com/understanding-and-using-rem-units-in-css/

    祝你好运!

    您可以通过更简单的代码获得所需的效果。看看:

    body {
      background-color: #27ae60;
    }
    
    .desk {
      position: relative;
      background-image: url(https://s13.postimg.org/li2l28a0n/White_Board.gif);
      width:560px;
      height:839px;
      margin: 0 auto;
    }
    
    .header { 
       padding: .5rem 0 0 2rem;
       font-size: 2.5rem;
       font-family: 'Just Me Again Down Here', cursive;
    }
    
    .answer { 
       width: 100%;
       margin-left: 2rem;
       outline: none;
       border: none;
       background-color: transparent;
       overflow: hidden;
       resize: none;
       font-size: 2rem;
       font-family: 'Just Me Again Down Here', cursive;
    }
    

    小提琴:https://jsfiddle.net/y3h1ogms/5/

答案 1 :(得分:1)

在元素上设置position: relative时,它将相对于最近的定位祖先定位,其中“定位”根据MDN表示:

  

定位元素是一个元素,其计算位置属性为相对,绝对,固定或粘性。

在您的示例中,标题不是图像的后代,因此无法相对于图像定位它。您可以做的是将<img>转换为<div>,将您的div的background-image设置为图片网址。您还需要明确设置div的宽度和高度。