Have a different color before and after a div with CSS

Here is an easier idea with background coloration:

.section {
  background:linear-gradient(to right,red 50%,blue 0);
}

.section .container {
  background-color: #fff;
  width: 250px;
  margin: 0 auto;
  text-align: center;
}

.section .container h1 {
  padding: 10px;
}
<div class="section">
  <div class="container">
    <h1>Hello world.</h1>
  </div>
</div>

You can still optimize more with only one container and multiple background:

.container {
  background:
   linear-gradient(#fff,#fff) center/250px 100% no-repeat,
   linear-gradient(to right, red 50%, blue 0);
  text-align: center;  
  padding:10px 0;

}

.container h1 {
  margin:0 auto;
  max-width:250px;
}
<div class="container">
  <h1>Hello world.</h1>
</div>

Another way with transparency:

.container {
  background:
   linear-gradient(red,red) left,
   linear-gradient(blue,blue) right;
  background-size:calc(50% - (250px/2)) 100%;
  background-repeat:no-repeat;
  text-align: center;  
  padding:10px 0;
}

.container h1 {
  margin:0 auto;
  max-width:250px;
}

body {
 background:pink;
}
<div class="container">
   <h1>Hello world.</h1>
</div>

Another syntax for the transparent one:

.container {
  background:
   linear-gradient(to right,
    red calc(50% - (250px/2) - 1px),transparent calc(50% - (250px/2)),
    transparent calc(50% + (250px/2)),blue calc(50% + (250px/2) + 1px));
  text-align: center;  
  padding:10px 0;
}

.container h1 {
  margin:0 auto;
  max-width:250px;
}

body {
 background:pink;
}
<div class="container">
   <h1>Hello world.</h1>
</div>

I have updated this using :before and :after, use this below code:

.section {
  width: 100%;
  position: relative;
}

.section .container {
  background-color:#fff;
  width: 250px;
  margin: 0 auto;
  text-align:center;
}
.section .container::before {
    background-color: red;
    content: ' ';
    width: 50%;
    height: 100%;
    position: absolute;
    left: 0;
    z-index: -1;
}
.section .container::after {
  background-color: blue;
  content: ' ';
    width: 50%;
    height: 100%;
    position: absolute;
    right: 0;
    z-index: -1;
    top: 0;
}

.section .container h1 {
  padding: 10px;
}
<div class="section">
  <div class="container">
    <h1>Hello world.</h1>
  </div>
</div>

Tags:

Html

Css