我有以下 HTML 用于将外部 div 居中并包含背景图像。这很好用。我想创建一个相对于图像大小的内部 div,以将 div 放置在图像中的黑色方 block 中。图像大小为 1783x1481,内部 div 的 Angular 应为 TopLeft:397,318 TopRight:1140,318 BottomLeft:397,903 BottomRight:1140,903
我不确定如何处理这个问题,我可以使用百分比吗?我应该使用 View 高度缩放吗?
#outer {
position: relative;
background-image: url(https://jrwr.io/terminal.png);
background-repeat: no-repeat;
background-position: center;
background-size: contain;
height: 100vh;
margin-left: auto;
margin-right: auto;
display: block;
}
<div id="outer">
<div id="inner">Example Text here</div>
<div>
最佳答案
如果你想用视口(viewport)缩放图像而不扭曲它,你可以使用 aspect-ratio
属性:
* {
margin: 0;
padding: 0;
}
html,
body {
background-color: rgb(78, 3, 78);
overflow: hidden;
}
#outer {
position: relative;
background-color: rgb(78, 3, 78);
background-image: url(/image/QhkFU.png);
background-repeat: no-repeat;
background-position: center;
background-size: contain;
margin: auto;
width: calc(min(100vw, 120vmin - 10px));
/* aspect ratio calculates the height */
aspect-ratio: 1.2/1;
}
#inner {
position: absolute;
top: 21%;
left: 22%;
width: 42%;
height: 40%;
background-color: black;
font: 2vmin monospace;
color: limegreen;
}
<div id="outer">
<div id="inner">
<br>
<p> Testing Terminal</p> > <span>ping www.google.com -t </span></div>
</div>
这里,宽度设置为calc(min(100vw, 120vmin - 10px))
。
- 如果视口(viewport)高度(vh) > 视口(viewport)宽度(vw),则vmin = vw,将使用
100vw
,图像高度将根据纵横比自动计算(1783/1481= 1.2). - 如果 vh < vw 那么,vmin = vh。宽度将设置为 vh 的 120%。
-10px
用于避免滚动条。您可以在主体上使用overflow:hidden
。
关于html - 内部 div 相对于背景图像的 CSS 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70118487/