首页 > 解决方案 > 如何使绝对定位的元素在需要为窗口的 50% 时对齐中心

问题描述

我需要制作一个宽度为“内容包装器”宽度的 50% 的横幅,并且该内容包装器的大小动态调整为最大宽度(因此理论上可以是 0px-1330px)。内容包装器是这里的深灰色框。它包含网站的内容。在该内容中是从窗口一侧出现的横幅。此处的窗口恰好具有黑色轮廓的边界。

如何使用 HTML/CSS 使紫色容器的内容适合黑暗的“内容包装”,即使它是窗口的 50%,并且当我不知道具体内容时,内容与包装的左侧对齐宽度。

我已经尝试了各种数学,但我无法完全理解。我正在使用 CSSvar作为站点最大宽度,我可以使用varcalc完成这项工作,但没有组合工作。

在此处输入图像描述

标签: htmlcss

解决方案


这符合你的问题吗?

* {
    margin: 0;
    padding: 0;
    list-style: none;
}
.wrap {
    width: 100%;
    max-width: 500px;
    height: 100vh;
    margin: auto;
    background-color: #aaa;
}
.banner {
    width: 50%;
    background-color: #a0f;
    padding: 20px 20px 20px 0;
    position: relative;
    box-sizing: border-box;
}
.banner::before {
    content: '';
    position: absolute;
    background-color: #a0f;
    top: 0;
    left: calc(100% - 50vw);
    height: 100%;
    width: calc(50vw - 100%);
}
<div class="wrap">
    <h1>Content Wrapper</h1>
    <div class="banner-wrap">
        <div class="banner">
            <h2>The title here</h2>
            <p>Some other text here</p>
        </div>
    </div>
</div>


推荐阅读