gpt4 book ai didi

html - 如何在容器宽度为百分比的情况下使用绝对位置在图像上定位文本

转载 作者:太空宇宙 更新时间:2023-11-04 09:57:28 26 4
gpt4 key购买 nike

我一直在练习 CSS 和 HTML,在为页面创建布局时我遇到了这个问题,这是第一个代码。注意:以下代码只是我在创建布局时遇到的问题示例

 <!DOCTYPE html>
<html>
<head>
<style>
*
{margin:0px;padding:0px;box-sizing:border-box;}
#container
{
width:800px;
position:relative;
background-color:darkgray;
}

#temp
{
position: relative;
}
#content
{
position:absolute;
top:100px;
right:120px;
width:200px;
height:200px;
border:1px solid yellow;
}
</style>
</head>
<body>
<div id="container">
<div id="temp">
<img src="psp.jpg" alt="no imgage">
<div id="content">
<h1>
Goku Vs Vegeta
<form>
<input type="text" placeholder="Start fighting" name="img">
</form>
</h1>
</div>
</div>
</div>
</body>
</html>

上面的代码对我来说非常有效,无论我们增加还是减少浏览器的缩放,文本都保持在图像上,文本不会改变它的位置。

当我将容器宽度从像素更改为百分比时,问题就来了,这里是第二个代码。

<!DOCTYPE html>
<html>
<head>
<style>
*
{margin:0px;padding:0px;box-sizing:border-box;}
#container
{
width:100%;
position:relative;
background-color:darkgray;
}

#temp
{
position: relative;
}
#content
{
position:absolute;
top:100px;
right:120px;
width:200px;
height:200px;
border:1px solid yellow;
}
</style>
</head>
<body>
<div id="container">
<div id="temp">
<img src="psp.jpg" alt="no imgage">
<div id="content">
<h1>
Goku Vs Vegeta
<form>
<input type="text" placeholder="Start fighting" name="img">
</form>
</h1>
</div>
</div>
</div>
</body>
</html>

第二个代码的问题是,如果我们增加或减少浏览器的缩放,文本的位置将会改变,它不会相对于图像,而是相对于浏览器的查看端口或容器而不是相对于图像。有人可以告诉我如何解决这个问题吗?

JS fiddle :https://jsfiddle.net/30d2nqeL/

最佳答案

        * {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}

#container {
width: 100%;
position: relative;
background-color: darkgray;
}

#temp {
position: relative;
background-image: url('http://lorempixel.com/1336/768');
background-size: cover;
height: 400px;
padding: 0 10vh;
}

#content {
position: absolute;
top: 50%;
margin-top: -100px;
right: 0;
margin-right: 10%;
width: 200px;
height: 200px;
border: 1px solid yellow;
background-color: rgba(255,255,255,.4);
}

#content h1 {
text-align: center;
margin: 1em 0 1em 0;
color: #000;
}
#content form {
text-align: center;
}
<div id="container">
<div id="temp">
<div id="content">
<h1>Goku Vs Vegeta</h1>
<form>
<input type="text" placeholder="Start fighting" name="img">
</form>
</div>
</div>
</div>

关于html - 如何在容器宽度为百分比的情况下使用绝对位置在图像上定位文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38599970/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com