Home > Back-end >  How to create different position background in one page in css
How to create different position background in one page in css

Time:11-09

How can I create a background with four different colour and four different position like the picture below using css yet without pushing down the content of html? enter image description here

CodePudding user response:

background-image in CSS allows you to have multiple images and to size them and position them individually.

linear-gradient(acolor,acolor) will give you a block of one color.

So putting these ideas together this snippet just puts the 4 colors (linear-gradients) positioned in the viewport as an example. As they are backgrounds they don't affect the positioning of any element.

html {
  width: 100vw;
  height: 100vh;
  background-image: linear-gradient(green, green), linear-gradient(magenta, magenta), linear-gradient(teal, teal), linear-gradient(orange, orange);
  background-size: 50% 25%;
  background-position: left top, right 33.333333%, left 66.666666%, right bottom;
  background-repeat: no-repeat;
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can use linear-gradient to create different colors at different points. However, this will not work directly the way you want it as linear-gradient works only into one direction. As such we have to create pseudo-elements for the left and the right 50%:

body {
  position: relative;
}

/* for the left 50% of the background */
body::before {
  content: "";
  position: absolute;
  top: 0;
  right: 50%;
  bottom: 0;
  left: 0;
  background: linear-gradient(to bottom, green 0 25%, white 25% 50%, #50A9B2 50% 75%, white 75% 100%);
  z-index: -1;
}

/* for the right 50% of the background */
body::after {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 50%;
  background: linear-gradient(to bottom, white 0 25%, purple 25% 50%, white 50% 75%, orange 75% 100%);
  z-index: -1;
}


/* for styling purpose only */
body {
  min-height: 100vh;
  margin: 0; 
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related