Two-tone background split by diagonal line using css

前端 未结 4 2039
误落风尘
误落风尘 2020-11-28 08:06

I am trying to create a background using css where one side is a solid color and the other is a texture: the two are split by a diagonal line. I would like this to be 2 sepa

4条回答
  •  孤独总比滥情好
    2020-11-28 08:51

    For this sort of thing you could use pseudo selectors such as :before or :after in your CSS to minimize on unnecessary HTML markup.

    HTML:

    CSS:

    #container {
        position: relative;
        height: 200px;
        width: 200px;
        overflow: hidden;
        background-color: grey;
    
    }
    
    #container:before { 
        content: '';
        position: absolute;
        left: 20%;
        width: 100%; 
        height: 200%; 
        background-color: rgb(255, 255, 255); /* fallback */
        background-color: rgba(255, 255, 255, 0.5);
        top: 0;
        -webkit-transform: rotate(45deg);
        -moz-transform: rotate(45deg);
        transform: rotate(45deg);
    }
    

    JSFiddle

    I then attempted to to make it so that each section could expand depending on where you clicked. This unfortunately requires a little extra jQuery as the position of your click (relative to the the box) needs to be worked out.

    A class is then added to the box which changes the :before pseudo object. The upside of using a class is that CSS animations are optimized better for the browser than jQuery ones.

    JSFiddle

    Resources:

    Selecting and manipulating CSS pseudo-elements such as ::before and ::after using jQuery

    Using jQuery how to get click coordinates on the target element

提交回复
热议问题