CSS: background-color only inside the margin

后端 未结 4 1655
梦如初夏
梦如初夏 2020-12-25 09:53

I have searched for an answer but couldn\'t find it anywhere. My question is reasonably simple: I have a background color of my body, then a large margin, and now I want a d

相关标签:
4条回答
  • 2020-12-25 10:25

    I needed something similar, and came up with using the :before (or :after) pseudoclasses:

    #mydiv {
       background-color: #fbb;
       margin-top: 100px;
       position: relative;
    }
    #mydiv:before {
       content: "";
       background-color: #bfb;
       top: -100px;
       height: 100px;
       width: 100%;
       position: absolute;
    }
    

    JSFiddle

    0 讨论(0)
  • 2020-12-25 10:28

    That is not possible du to the Box Model. However you could use a workaround with css3's border-image, or border-color in general css.

    However im unsure whether you may have a problem with resetting. Some browsers do set a margin to html as well. See Eric Meyers Reset CSS for more!

    html{margin:0;padding:0;}
    
    0 讨论(0)
  • 2020-12-25 10:31

    Instead of using a margin, could you use a border? You should do this with <div>, anyway.

    Something like this?enter image description here

    http://jsfiddle.net/GBTHv/

    0 讨论(0)
  • 2020-12-25 10:44

    If your margin is set on the body, then setting the background color of the html tag should color the margin area

    html { background-color: black; }
    body { margin:50px; background-color: white; }
    

    http://jsfiddle.net/m3zzb/

    Or as dmackerman suggestions, set a margin of 0, but a border of the size you want the margin to be and set the border-color

    0 讨论(0)
提交回复
热议问题