CSS中具有相对位置的文本重叠图像



我想让我的文本在相对位置上重叠在这个图像上,同时也保持在100vmin的边界内。这是我的HTML代码。我知道图像不会显示在Stack Overflow上,但图像是一个SVG文件。SVG是一个精确的方形,在SVG文件(作为txt文件(中宽度和高度分别为332。

<!DOCTYPE html>
<!-- Created and Copyright of MrEthanVlogsandGames -->
<html lang="en">
<head>
<title>Test</title>
<link rel="icon" href="/images/tab_icon.svg">
<style>
/******
FONTS
******/
@import url('https://fonts.googleapis.com/css?family=Roboto');
/******
EVERYTHING ELSE
******/
body {
font-family: Roboto;
width: 100vw;
height: 100vh;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
background-color: #000;
}
ul {
display: inline-block;
}
.app {
width: 100vmin;
height: 100vmin;
}
.starting_page > img {
display: block;
width: 100%;
z-index: 1;
}
p.text {
display: block;
position: relative;
text-align: center;
font-weight: bold;
color: #fff;
text-align: center;
z-index: 2;
}
</style>
</head>
<body>
<div class="app">
<div class="starting_page">
<img src="/images/starting_page.svg">
<p class="text">Overlapping Text</p>
</div>
</div>
</body>
</html>

position: relative需要在父元素上,然后在要重叠的元素上使用position: absolute,并使用topleft等将它们定位在relative父元素中。

从技术上讲,你可以用position: relativetopleft等来移动一个元素,但问题是它在原始位置仍然会占用空间。上面的方法没有这个问题。

body {
font-family: Roboto;
width: 100vw;
height: 100vh;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
background-color: #000;
}
.app {
position: relative;
width: 100vmin;
height: 100vmin;
}
.starting_page>img {
display: block;
width: 100%;
z-index: 1;
}
p.text {
display: block;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%);
text-align: center;
font-weight: bold;
color: #fff;
z-index: 2;
}
<div class="app">
<div class="starting_page">
<img src="https://picsum.photos/332">
<p class="text">Overlapping Text</p>
</div>
</div>

最新更新