我正在尝试弄清楚如何使用 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>
最佳答案
首先我们设置一个带有
.desk
类的 div,desk 将接收所需的背景图像、固定的宽度和高度,并且它会margin 0 auto
因为 table 上没有容器。.header
类不需要是绝对的,我们在已经相对定位的 table 内使用它。我们对其进行了一些填充,使其适合桌面图像。.answer
类应用于textarea
元素,我们给它一个width 100%;
因为我们在内部使用它.desk
已经有预定义的宽度,这意味着.answer
将在 table 内配备所有可能的宽度。
一个很好的技巧是在 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/
关于javascript - 使用位置 : relative; 在图片区域内包含文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39378284/