div 左右半部分的背景颜色不同

问题描述 投票:0回答:7

我有一个居中的 div 布局。背景中的 div 左侧应为白色,右侧应为绿色。两者都应延伸至无穷大。

我认为这应该很简单,但我现在不明白。有什么简单的解决办法吗? 谢谢!

-----------------------------------------------------
(div 1)     __________________________ 
           |(div 2)         |         |
           |                |         |
           |                |         |
<- white   |     white      |  green  |   green  ->
           |                |         |
           |                |         |
           |________________|_________|

------------------------------------------------------
html css background center
7个回答
16
投票

使用

::after
::before
伪元素。这样你甚至可以得到三种颜色并制作意大利国旗!

div {
    height:300px;
    width:100%;
    outline:thin solid black;
    position:relative;
    background:white;
}
div::after, div::before {
    height:300px;
    content:' ';
    position: absolute;
    top: 0;
    width: 33%;
}
div::after {
    right: 0;
    background-color: red;
}
div::before {
    left: 0;
    background-color: green;
}

这是一个小提琴:http://jsfiddle.net/g8p9pn1v/

其结果:enter image description here


7
投票

将具有两种颜色的背景图像添加到外部 div 并允许浏览器缩放它(而不是平铺它)。

每种颜色应恰好填充图像宽度的 50%,以确保颜色不会泄漏到两侧。

甚至可以将图像绝对定位在内部 div 后面。

有关如何拉伸图像的想法,请参阅此问题:CSS 背景重复


4
投票

如何创建两个 div bg-left 和 bg-right,在全宽容器内具有绝对位置。由于它们是绝对定位的,因此您可以将内容分层在它们之上。例如,使用引导标记:

<div class="fullwidth">
    <div class="bg-left"></div>
    <div class="bg-right"></div>    

    <div class="container">
        <div class="row">
            <div class="col-xs-6">
                Insert left side content here...
            </div>
            <div class="col-xs-6">
                Insert right side content here...
            </div>
        </div>
    </div>
</div>

然后你的CSS:

.fullwidth {
    position: relative;
    width: 100%;
 }
.bg-left {
    background: #000; 
    left: 0;
    top: 0;
    bottom: 0;
    position: absolute;
    width: 50%;
}
.bg-right {
    right: 0;
    top: 0;
    bottom: 0;
    background: #ddd; 
    position: absolute;
    width: 50%;
}

3
投票

2021年最简单的方法:

.container {
  background: linear-gradient(
    to right, 
    red 0%, 
    red 50%, 
    black 50%, 
    black  100%
  );
}

1
投票

您可以在外部放置两个 div,然后在每个 div 中放置一个您的 div。分别右对齐和左对齐。像这样:

-----------------------------------------------------
(div)                       | (div)
           _________________|_________ 
           |(div)           |  (div)  |
           |                |         |
           |                |         |
<- white   |     white      |  green  |   green  ->
           |                |         |
           |                |         |
           |________________|_________|
                            |
------------------------------------------------------

0
投票

我会在该 div 中放入另外两个 div 并给它们适当的大小和背景颜色


0
投票

您可以使用渐变。这是一个网站,您可以在其中获取您需要的跨浏览器代码。

http://colorzilla.com/gradient-editor/

刚开始使用时可能会有点困惑,但我发现它是一个非常强大的工具。

问候!

© www.soinside.com 2019 - 2024. All rights reserved.