将图像设置为屏幕的百分比,而不是像素

make the Image a percentage of the screen and not pixels?

本文关键字:像素 百分比 图像 设置 屏幕      更新时间:2023-09-26

对于我的web开发类,我有3个图像,一个当点击图像开始比赛,其他两个将在屏幕上比赛。在我家里的个人电脑上,屏幕上的图像几乎是完美的,当赛车图像结束时,它们会浏览开始它的图像。在学校里,在屏幕上移动的图像不会超过开始它的图像,因为它更高,其他两个图像更小,因为它是像素。我怎样才能让开始比赛的图像接近一半的屏幕大小,而其他两个图像,因为它们在彼此的顶部,它们将接近一半的大小?

我有JavaScript代码但那只是让图像移动

正文图片

<body>
<div id="location" class="clickme">
<input type="image" id="start" src="death.png" alt="dstar"  onclick="startRace()" class="img3">
</div>
<div class="raceTrack">
<img src="tie.png" id="1" alt="tie" class="img1">
<hr>
<img src="xwing.png" id="x-wing" alt="xwing" class="img2">
</div>
<div id="announce" class="hidden">
<span id="message">and the winner is...</span>
<img id="winner" src="1.png" alt="x-wing.png" >
</div>
</body>

样式代码

<style>
body { 
background-image: url(home.png); 
background-repeat: no-repeat;
background-size: 100%;
}
div.raceTrack {
position: fixed;
margin: auto;
bottom: 0px;
left: 0px;
}
div#location{
position: absolute;
top: 0px;
right: 0px;
}
img {
display: inline-block;
position: relative;
transition: all 0.2s;
}
div#announce {
position: fixed;
margin: auto;
top: 0px;
left: 0;
right: 0;
height: 10em;
width: 10em;
text-align: center;
transition: all 0.5s;
}
.hidden {
opacity: 0;
top: 0px;
bottom: 0px;
}
</style>

你应该在你的CSS中使用相对单位。

%相对于父(或最接近的固定单元)

vhvw从0到100,代表视口(窗口大小)

:

<div style="width: 500px;">
    <div style="width: 50%">This will be 50% of 500px</div>
    <div style="width: 50vw;">This will be 50% of window width</div>
</div>

使用vh(视口高度)和vw(视口宽度)也会自动调整,如果窗口的大小。