【问题标题】:Can I make a color background take up only a % of an element without making an image?我可以在不制作图像的情况下使彩色背景仅占元素的 % 吗?
【发布时间】:2023-04-03 11:43:01
【问题描述】:

如果我想在网页顶部的背景中有一个蓝色条(所以 body 元素的背景),但我希望它的高度为 100px 并跨越整个水平背景......有什么办法要做到这一点,而不用我想要的颜色制作一个 100 像素的背景图像(可能宽度为 1 像素)并使其重复-x?

基本上,而不是做:

background: url("images/pagestripe.png") repeat-x;

我想这样做:

background: #FFCCFF 100px top left repeat-x;

这会给我一个 100 像素的颜色 #FFCCFF 背景,从页面的左上角开始并水平重复。

同样,如果我想让它重复-y,它会将 100px 设为宽度而不是高度。

定位标记可以表示偏移量...

这可能吗?是否有我正在寻找的实际 CSS 代码?也许我已经不远了……

【问题讨论】:

    标签: css


    【解决方案1】:

    你可以使用linear gradients

    body {
        background-image: -moz-linear-gradient(top, blue 100px, transparent 0);
        background-image: -o-linear-gradient(top, blue 100px, transparent 0);
        background-image: -webkit-linear-gradient(top, blue 100px, transparent 0);
        background-image: linear-gradient(top, blue 100px, transparent 0);
    }
    

    编辑:这只是 CSS3。对于 CSS2 你可以试试

    body:before {
        content: ' ';
        display: block;
        top: 0;
        position: absolute;
        height: 100px;
        width: 100%;
        background: blue;
    }
    

    【讨论】:

      【解决方案2】:

      您可以将条形设为单独的div 并在其上设置负边距。像这样的:

      <div id="bluebar"></div>
      Content goes here...
      

      然后在 CSS 中:

      div#bluebar {
          background: #fcf;  /* that's actually pink, but whatever... */
          height: 100px;
          margin-bottom: -100px;
      }
      

      我会提供一个 jsFiddle 链接,但它们现在显然正在维护中,所以改为 here's a simple static HTML demo

      【讨论】:

        【解决方案3】:

        可以的。

        您可以创建具有所需高度和背景颜色的单个全宽元素。

        使用 CSS 定位元素。

        div#bluebar {
            background: #acf;
            display: block;
            height:100px;
            width:100%;
            position: absolute;
            top: 0px; /* however far from the top you would like it*/
            left: 0px;
            z-index: 10; /* or some other number that will place it below the appropriate elements */
        }
        

        请确保#blubar 的父级没有设置position:relative;,否则它将相对于父级而不是文档定位。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-11-10
          • 2022-10-13
          • 2016-02-25
          • 2011-02-13
          • 1970-01-01
          • 2015-07-20
          • 2014-03-14
          • 1970-01-01
          相关资源
          最近更新 更多