CSS:设置为窗口宽度 50% 的背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8541081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 02:24:28  来源:igfitidea点击:

CSS: Set a background color which is 50% of the width of the window

cssbackground-color

提问by Staffan Estberg

Trying to achieve a background on a page that is "split in two"; two colors on opposite sides (seemingly done by setting a default background-coloron the bodytag, then applying another onto a divthat stretches the entire width of the window).

试图在“一分为二”的页面上实现背景;相对两侧的两种颜色(似乎是通过background-colorbody标签上设置默认值,然后将另一种颜色应用到div拉伸整个窗口宽度的a 上来完成的)。

I did come up with a solution but unfortunately the background-sizeproperty doesn't work in IE7/8 which is a must for this project -

我确实想出了一个解决方案,但不幸的是该background-size属性在 IE7/8 中不起作用,这是该项目必须的 -

body { background: #fff; }
#wrapper {
    background: url(1px.png) repeat-y;
    background-size: 50% auto;
    width: 100%;
}

Since it's just about solid colors maybe there is a way using only the regular background-colorproperty?

由于它只是纯色,也许有一种方法可以只使用常规background-color属性?

回答by justisb

Older Browser Support

旧浏览器支持

If older browser support is a must, so you can't go with multiple backgrounds or gradients, you're probably going to want to do something like this on a spare divelement:

如果旧浏览器支持是必须的,所以你不能使用多个背景或渐变,你可能想要在备用div元素上做这样的事情:

#background {
    position: fixed;
    top: 0;
    left: 0;
    width: 50%;
    height: 100%;
    background-color: pink; 
}

Example: http://jsfiddle.net/PLfLW/1704/

示例:http: //jsfiddle.net/PLfLW/1704/

The solution uses an extra fixed div that fills half the screen. Since it's fixed, it will remain in position even when your users scroll. You may have to fiddle with some z-indexes later, to make sure your other elements are above the background div, but it shouldn't be too complex.

该解决方案使用一个额外的固定 div 填充屏幕的一半。由于它是固定的,即使您的用户滚动,它也会保持原位。稍后您可能需要摆弄一些 z-index,以确保您的其他元素位于背景 div 之上,但它不应该太复杂。

If you have issues, just make sure the rest of your content has a z-index higher than the background element and you should be good to go.

如果您有问题,只需确保您的其余内容的 z-index 高于背景元素,您就可以开始使用了。



Modern Browsers

现代浏览器

If newer browsers are your only concern, there are a couple other methods you can use:

如果您只关心较新的浏览器,您可以使用其他几种方法:

Linear Gradient:

线性渐变:

This is definitely the easiest solution. You can use a linear-gradient in the background property of the body for a variety of effects.

这绝对是最简单的解决方案。您可以在主体的背景属性中使用线性渐变来实现各种效果。

body {
    height: 100%;
    background: linear-gradient(90deg, #FFC0CB 50%, #00FFFF 50%);
}

This causes a hard cutoff at 50% for each color, so there isn't a "gradient" as the name implies. Try experimenting with the "50%" piece of the style to see the different effects you can achieve.

这会导致每种颜色的硬截止为 50%,因此没有顾名思义的“渐变”。尝试尝试使用“50%”风格的部分,看看您可以实现的不同效果。

Example: http://jsfiddle.net/v14m59pq/2/

示例:http: //jsfiddle.net/v14m59pq/2/

Multiple Backgrounds with background-size:

具有背景大小的多个背景:

You can apply a background color to the htmlelement, and then apply a background-image to the bodyelement and use the background-sizeproperty to set it to 50% of the page width. This results in a similar effect, though would really only be used over gradients if you happen to be using an image or two.

您可以将背景颜色应用于html元素,然后将背景图像应用于body元素并使用该background-size属性将其设置为页面宽度的 50%。这会产生类似的效果,但如果您碰巧使用一两个图像,实际上只会在渐变上使用。

html {
    height: 100%;
    background-color: cyan;
}

body {
    height: 100%;
    background-image: url('http://i.imgur.com/9HMnxKs.png');
    background-repeat: repeat-y;
    background-size: 50% auto;
}

Example: http://jsfiddle.net/6vhshyxg/2/

示例:http: //jsfiddle.net/6vhshyxg/2/



EXTRA NOTE:Notice that both the htmland bodyelements are set to height: 100%in the latter examples. This is to make sure that even if your content is smaller than the page, the background will be at least the height of the user's viewport. Without the explicit height, the background effect will only go down as far as your page content. It's also just a good practice in general.

额外说明:请注意,在后面的示例中,htmlbody元素都设置为height: 100%。这是为了确保即使您的内容小于页面,背景也至少是用户视口的高度。如果没有明确的高度,背景效果只会下降到您的页面内容。总的来说,这也是一种很好的做法。

回答by juniperi

Simple solution to achieve "split in two" background:

实现“一分为二”背景的简单解决方案:

background: linear-gradient(to left, #ff0000 50%, #0000ff 50%);

You can also use degrees as direction

您还可以使用度数作为方向

background: linear-gradient(80deg, #ff0000 50%, #0000ff 50%);

回答by akash

You can make a hard distinction instead of linear gradient by putting the second color to 0%

您可以通过将第二种颜色设置为 0% 来进行硬区分而不是线性渐变

For instance,

例如,

Gradient - background: linear-gradient(80deg, #ff0000 20%, #0000ff 80%);

坡度 - background: linear-gradient(80deg, #ff0000 20%, #0000ff 80%);

Hard distinction - background: linear-gradient(80deg, #ff0000 20%, #0000ff 0%);

硬区分—— background: linear-gradient(80deg, #ff0000 20%, #0000ff 0%);

回答by WebWanderer

So, this is an awfully old question which already has an accepted answer, but I believe that this answer would have been chosen had it been posted four years ago.

所以,这是一个非常古老的问题,已经有一个公认的答案,但我相信,如果这个答案在四年前发布,就会被选中。

I solved this purely with CSS, and with NO EXTRA DOM ELEMENTS! This means that the two colors are purely that, just background colors of ONE ELEMENT, not the background color of two.

我完全用 CSS 解决了这个问题,没有额外的 DOM 元素!这意味着这两种颜色纯粹是一个元素的背景颜色,而不是两个的背景颜色。

I used a gradient and, because I set the color stops so closely together, it looks as if the colors are distinct and that they do not blend.

我使用了渐变,并且因为我将颜色停止点设置得如此紧密,所以看起来颜色是不同的并且它们不混合。

Here is the gradient in native syntax:

这是本机语法的渐变:

background: repeating-linear-gradient(#74ABDD, #74ABDD 49.9%, #498DCB 50.1%, #498DCB 100%);

Color #74ABDDstarts at 0%and is still #74ABDDat 49.9%.

颜色#74ABDD从 开始0%并且仍然#74ABDD49.9%

Then, I force the gradient to shift to my next color within 0.2%of the elements height, creating what appears to be a very solid line between the two colors.

然后,我强制渐变切换到0.2%元素高度内的下一个颜色,在两种颜色之间创建一条看起来非常实线的线。

Here is the outcome:

结果如下:

Split Background Color

拆分背景色

And here's my JSFiddle!

而且,这里是我的jsfiddle!

Have fun!

玩得开心!

回答by Michael

this should work with pure css.

这应该适用于纯 css。

background: -webkit-gradient(linear, left top, right top, color-stop(50%,#141414), color-stop(50%,#333), color-stop(0%,#888));

tested in Chrome only.

仅在 Chrome 中测试。

回答by Putuko

In a past project that had to support IE8+ and I achieved this using a image encoded in data-url format.

在过去必须支持 IE8+ 的项目中,我使用以 data-url 格式编码的图像实现了这一点。

The image was 2800x1px, half of the image white, and half transparent. Worked pretty well.

图像为 2800x1px,图像的一半为白色,一半为透明。工作得很好。

body {
    /* 50% right white */
    background: red url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAACvAAAAABAQAAAAAqT0YHAAAAAnRSTlMAAHaTzTgAAAAOSURBVHgBYxhi4P/QAgDwrK5SDPAOUwAAAABJRU5ErkJggg==) center top repeat-y;

   /* 50% left white */
   background: red url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAACvAAAAABAQAAAAAqT0YHAAAAAnRSTlMAAHaTzTgAAAAPSURBVHgBY/g/tADD0AIAIROuUgYu7kEAAAAASUVORK5CYII=) center top repeat-y;
}

You can see it working here JsFiddle. Hope it can help someone ;)

你可以看到它在这里工作JsFiddle。希望它可以帮助某人;)

回答by user1162084

I have used :afterand it is working in all major browsers. please check the link. just need to careful for the z-index as after is having position absolute.

我已经使用过:after并且它可以在所有主要浏览器中运行。请检查链接。只需要注意 z-index,因为它具有绝对位置。

<div class="splitBg">
    <div style="max-width:960px; margin:0 auto; padding:0 15px; box-sizing:border-box;">
        <div style="float:left; width:50%; position:relative; z-index:10;">
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.
        </div>
        <div style="float:left; width:50%; position:relative; z-index:10;">
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, 
        </div>
        <div style="clear:both;"></div>
    </div>
</div>`
css

    .splitBg{
        background-color:#666;
        position:relative;
        overflow:hidden;
        }
    .splitBg:after{
        width:50%;
        position:absolute;
        right:0;
        top:0;
        content:"";
        display:block;
        height:100%;
        background-color:#06F;
        z-index:1;
        }

fiddle link

小提琴链接

回答by Awaterujin

You could use the :afterpseudo-selector to achieve this, though I am unsure of the backward compatibility of that selector.

您可以使用:after伪选择器来实现这一点,但我不确定该选择器的向后兼容性。

body {
    background: #000000
}
body:after {
    content:'';
    position: fixed;
    height: 100%;
    width: 50%;
    left: 50%;
    background: #116699
}

I have used this to have two different gradients on a page background.

我用它在页面背景上有两种不同的渐变。

回答by Jan Ranostaj

Use on your image bg

在您的图像 bg 上使用

Vertical split

垂直分割

background-size: 50% 100%

Horizontal split

水平分割

background-size: 100% 50%

Example

例子

.class {
   background-image: url("");
   background-color: #fff;
   background-repeat: no-repeat;
   background-size: 50% 100%;
}

回答by Nadav

One of the way to implement your issue to input one single line inside your div:

实现问题的方法之一是在 div 中输入一行:

background-image: linear-gradient(90deg, black 50%, blue 50%);

Here is a demonstration code and more options (horizontal, diagonal, etc.), you can click on "Run code snippet" to see it live.

这里是一个演示代码和更多选项(水平、对角线等),你可以点击“运行代码片段”来实时查看。

.abWhiteAndBlack
{
  background-image: linear-gradient(90deg, black 50%, blue 50%);
  height: 300px;
  width: 300px;
  margin-bottom: 80px;
}

.abWhiteAndBlack2
{
  background-image: linear-gradient(180deg, black 50%, blue 50%);
  height: 300px;
  width: 300px;
  margin-bottom: 80px;
}

.abWhiteAndBlack3
{
  background-image: linear-gradient(45deg, black 50%, blue 50%);
  height: 300px;
  width: 300px;
  margin-bottom: 80px;
}
Vertical:

  <div class="abWhiteAndBlack">
  </div>


Horizonal:

  <div class="abWhiteAndBlack2">
    
  </div>


Diagonal:

  <div class="abWhiteAndBlack3">
    
  </div>