Maciej Wójcik Maciej Wójcik - 1 year ago 94
CSS Question

How to set background-color on 50% of area CSS

I want to have a div, and inside this div must be a field with some color. So i want to have div for example 200px x 200px and set background-color:gray which size ll be 100px x 100px, and start at position 50px 50px.

Please look at this snippet with code:

background-color: gray;
background-size: 100px 100px;
background-position: 50px 50px;



<div>some text</div>

So as You see the background color filled all div width and height.
Is this possible to make background to fill only 50%?
enter image description here

Note: The red area should be transparent.

Answer Source

We can achieve this effect with a linear gradient, background-size and background-position

  • The background looks like this:

    background:  linear-gradient(to bottom, grey 0%, grey 100%) no-repeat;

    All this linear-gradient does is give us a background colour that can be manipulated like a background image.

  • The gradient is treated like an image and can be centered and re-sized

    background-size: calc(100% - 100px);
    background-position: center;

The calc reduces the size of the background by exactly 100px and the transparent space around the div when centered is 50px in width.

Full example

The second div shows the true size of the div and the 20vw width and height shows how the div can be re-sized.

div {
  background: linear-gradient(to bottom, grey 0%, grey 100%) no-repeat;
  background-position: center;
  background-size: calc(100% - 100px); /* 100px is the total for each axis (50px + 50px)*/
  padding: 80px;  /* 50px border + 30px additional padding */
  width: 20vw;
  height: 20vw;
  min-width: 200px;
  min-height: 200px;
} {
  background: grey;
/*For example*/

body {
  height: 100%;
  margin: 0;
body {
  background: linear-gradient(to bottom, black 0%, white 100%);
div {
  display: inline-block;
<div>some text</div>
<div class="no-gradient">I am the same size as the other div</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download