Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

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:

div{
    background-color: gray;
    background-size: 100px 100px;
    background-position: 50px 50px;
    
    min-width:200px!important;
    min-height:200px!important;
    max-width:200px!important;
    max-height:200px!important; 
      
    padding: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.

like image 913
Maciej Wojcik Avatar asked Dec 15 '22 03:12

Maciej Wojcik


1 Answers

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) 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-size: calc(100% - 100px) calc(100% - 100px); /* Reduce height of background by 100px and width by 100px*/  
  background-position: center;
  padding: 80px;  /* 50px border + 30px additional padding */
  width: 20vw;
  height: 20vw;
  min-width: 200px;
  min-height: 200px;
}
div.no-gradient {
  background: grey;
}
/*For example*/

html,
body {
  height: 100%;
  margin: 0;
}
body {
  background: linear-gradient(to bottom, black 0%, white 100%);
}
div {
  float: left;
}
<div>some text</div>
<div class="no-gradient">I am the same size as the other div</div>
like image 74
misterManSam Avatar answered Feb 02 '23 00:02

misterManSam