首页 > 解决方案 > 将 HTML 元素(固定)放置在另一个元素的顶部,不重叠,在窗口调整大小时保持恒定间距

问题描述

我有一个 div 元素,它有一个以它为中心的背景图像。我希望将 h2 或 p 元素定位(固定或绝对,不确定哪个是正确的)在该 div 元素之上,但不重叠它。即使调整窗口大小,它也应该具有相同的下边距。我已经尝试在带有背景图像的 div 中放置一个innerText 。我添加了这样的图像:

<div>    
<!-- other elements -->
   <div class="v-container visible default background-image">
</div>

在 CSS 中:

.v-container {
    background-color: #e9e9e9;
    text-align: center;
    font-family: cursive;
}

.default {
    background-color: rgba(0, 0, 0, 0.103);
    width: 100%;
    height: 100%;
    pointer-events: none;
}

.background-image {
    background-image: url('../graphics/Note.png');
    background-position: center;
    background-repeat: no-repeat;
}

在此处输入图像描述

标签: htmlcsselectron

解决方案


我尝试了一段时间来解决我的问题,我想我已经得到了我的问题的答案。好吧,这不完全是我需要的答案,但它为图像上方的元素提供了图像与其父容器顶部之间的恒定间距。我使用top: x%and bottom: -x%CSS 属性实现了这一点。其中x代表所需的百分比。例如,top: 15%bottom: -15%实现了同样的事情。我不确定为什么在使用该bottom属性时必须使用“-”符号,但它确实有效。下面的示例代码说明了我是如何实现这一目标的:

HTML

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NoteBook 2.0</title>
    <link rel="stylesheet" href="../styles/photon.css">
    <link rel="stylesheet" href="../styles/main.css">
    <script src="../UI/renderer.js" async defer></script>
</head>

<body>    
     <div class="invisible default v-container">
        <h4>Tap a note on the left to view here</h4>
        <h5>Or Tap the&nbsp;
            <span class="icon icon-book"></span> &nbsp;icon at the left to add new note
        </h5>
        <img src="../graphics/Hand_note.png" alt="Note icon">
     </div>

</body>

</html>

样式表 (CSS)

html, body {
        width: 100%;
        height: 100%;
}
    
.v-container {
        background-color: #e9e9e9;
        text-align: center;
    }
    
    .v-container :first-child {
        position: relative;
        top: 15%;
    }
    
    .v-container :nth-child(2) {
        position: relative;
        top: 15%;
    }
    
    .v-container :last-child {
        position: relative;
        top: 20%;
    }

结果:

在此处输入图像描述

从图像上看,它看起来很正常,但是当您调整窗口大小时,图像仍然与其他元素保持恒定间距。顶部的文本始终在其父元素上保持 15%,因为它position被设置为relative. 第一个元素子元素下方的文本元素也设置了 15% (我猜,这意味着,因为位置也设置为relative,它仍然遵循子元素在父容器中出现的顺序。


推荐阅读