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

Contain Text within Picture area using Position: relative;

我正在尝试弄清楚如何使用 Position: relative 来将对象(我们称之为文本)保留在屏幕上的同一位置,而不管屏幕尺寸如何。

当我使用 Position: relative 时,例如将 "left" 设置为 30%...它是屏幕的 30%。我想弄清楚如何将文本放在图像顶部并将文本设置为图像中剩余 30%。无论屏幕尺寸如何,我都需要它来工作。到目前为止,我一直做不到。

有人可以向我解释一下 Position Relative 和 Position Absolute 在这种情况下是如何工作的吗?或者最好如何处理?

谢谢!

这是我的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>

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

  2. .headerclass不需要是绝对的,我们在已经相对定位的桌子内使用。我们给它一点填充,使其适合桌面图像。

  3. .answer class 应用于 textarea 元素我们给它一个 width 100%; 因为我们在 [=11= 中使用它] 已经有预定义的宽度,这意味着 .answer 将在桌子内配备所有可能的宽度。

一个很好的技巧是在 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;
}

Fiddle: https://jsfiddle.net/y3h1ogms/5/

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

A positioned element is an element whose computed position property is either relative, absolute, fixed or sticky.

在您的示例中,header 不是图像的后代,因此无法相对于图像定位它。您可能要做的是将 <img> 转换为 <div>,将 div 的 background-image 设置为图像 URL。您还需要明确设置 div.

的宽度和高度