【问题标题】:Can the angle of the gradient be made dependent of the width of the container?渐变的角度可以取决于容器的宽度吗?
【发布时间】:2014-07-05 05:32:45
【问题描述】:

所以我有两个相邻的流体 div,它们可以在设备大小改变、用户改变浏览器的字体大小或使用 Ctrl + 缩放浏览器时改变它们的宽度。

我希望有一条穿过两个 div 的对角线,如下所示:

_____
|blah|
|blah|
|blah| 
|   /| <--- First div or section
|__/_|
| /  | <--- Second div or section
|/   |
|blah|
|blah|
|blah|
|____| 
<----> fluid width

我正在尝试使用 CSS 来避免下载图像和发出额外的 http 请求。所以我使用线性渐变。问题是当其容器的宽度增加或减小时,对角线的角度必须改变,否则对角线会断裂。

在这里查看小提琴:http://dabblet.com/gist/50db5e6220b5ba557b9e

记录一下,上面fiddle的代码是:

/*
* Diagonal that crosses both divs without breaking
*/
div, p{margin:0;}
div{padding:0 1em;}
.one{
    background: #f06;
    background: linear-gradient(170deg, #f06 80%, yellow 80%, yellow);
    font-size: 200%
}
.two{
    background: yellow;
    background: linear-gradient(170deg, #f06 20%, yellow 20%, yellow);
    font-size: 200%
}

还有html:

<div class="one"><!-- foo --></div>
<div class="two"><!-- bar --></div>

我尝试更改背景大小、背景位置、背景原点、单位从 em 到 px、从 px 到 %、颜色停止等。我没有想法了。

我的问题是...有没有办法使渐变中的角度取决于容器的宽度(以某种间接方式),以便如果调整大小,对角线会改变其角度?我想要一个纯 CSS 解决方案(没有 JavaScript)。

如果这是一个没有解决方案的问题,没关系=)

【问题讨论】:

    标签: css fluid-layout gradient angle


    【解决方案1】:

    您可以使用此解决方法:

    <div class="wrapper">
        <div class="bg"></div>
        <div class="one"><!-- foo --></div>
        <div class="two"><!-- bar --></div>
    </div>
    
    .wrapper {
        position: relative;
    }
    .bg {
        z-index: -1;
        position: absolute;
        top: 0; right: 0; bottom: 0; left: 0;
        background: linear-gradient(to bottom right, #f06 50%, yellow 50%, yellow);
    }
    

    Demo

    【讨论】:

    • @Eric 解决方法是将背景设置为.bg,而不是在.one.two 之间拆分。
    • 感谢您抽出宝贵时间尝试! =) 将 bg 设置在另一个元素中以便它很好地适应是一个聪明的主意。但是,为了样式,您需要添加一个额外的 div,这不是很好。但是,这个想法仍然很酷,所以I decided to try with pseudo elements instead (using :before)。问题是 div 的内容需要设置更高的 z-index。我会继续思考...再次感谢您!
    【解决方案2】:

    我猜你可以使用背景大小和无重复来做到这一点。 DEMO

    .one{
        background: #f06;
        background: linear-gradient(to bottom right, #f06 50%, yellow 50%, yellow) right  #f06 ; 
        background-size: 50% 100%;  100% 50% ;
        background-repeat:no-repeat;
        font-size: 200%
    }
    .two{
        background: yellow;
        background: linear-gradient(to bottom right, #f06 50%, yellow 50%, yellow) left yellow ; 
        background-size: 50% 100%;  100% 50% ;
        background-repeat:no-repeat;
        font-size: 200%
    }
    

    但是,如果两个 div 的高度不同,这看起来会很有趣:DEMO

    You better set the gradient within the parent container (body for your dabblet) 在我个人看来,除非你确实想看到渐变角度的变化。

    【讨论】:

    • 感谢您的回答。没错,我只关注响应测试的宽度,但高度也会影响角度。在父容器中设置渐变的问题之一是会有两个以上的 div,但是你的解决方案给了我更多的想法来测试。我会尝试找到一些解决方法。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    相关资源
    最近更新 更多