Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the width of background-color of a div?

Tags:

html

css

I have two divs with same background color. How can I set the width of background?

Expected result:

enter image description here

Here is HTML:

<div>
    <span>100% width of background</span>
</div>
<div>
    <span>75% width of background</span>
</div>

What I tried to do using CSS:

div {
    background-color: #fc0;
    margin: 2px;
}
div:last-child {
    background-size: 75%;
}

jsFiddle, of course.

Is it posible to do this exept of setting width of a div?

like image 538
Vlad Holubiev Avatar asked Mar 22 '23 14:03

Vlad Holubiev


1 Answers

You can use background gradients with hard stops. Here I'm using custom properties on each element to dynamically set the length value. The CSS rule uses a partial attribute selector to look for the custom property in the style attribute.

div {
  background-color: #fc0;
  margin: 2px;
}

div[style*="--bg-length"] {
  background: linear-gradient(
    to right, 
    #fc0 var(--bg-length), /* the end of the colored segment */
    transparent var(--bg-length) /* the start of the transparent segment */
  );
}
<div><span>100% width of background</span></div>
<div style="--bg-length: 300px"><span>60% width of background</span></div>
<div style="--bg-length: 85%"><span>85% width of background</span></div>
<div style="--bg-length: 70vw"><span>85% width of background</span></div>
like image 52
isherwood Avatar answered Mar 31 '23 14:03

isherwood