CSS: unset and "not set" difference

Viewed 509

Is there any difference between setting a css property to the unset value or not setting it at all?

#element {
    border: unset;
}

#element {
    /*nothing here!*/
}

Also, is the javascript set to empty string equivalent to setting to unset?

element.style.border = "";
element.style.border = "unset"; //same effect always?
2 Answers

From MDN DOCS:

The unset CSS keyword resets a property to its inherited value if the property naturally inherits from its parent, and to its initial value if not. In other words, it behaves like the inherit keyword in the first case, when the property is an inherited property, and like the initial keyword in the second case, when the property is a non-inherited property.

unset can be applied to any CSS property, including the CSS shorthand all.

In your first case:

#element {
    border: unset; // Here the border is set to its default value 
}

#element {
    /*nothing here!*/ In this case you have not used any CSS property on the element so border remains its default value 
}

In your second part: No they "" and "unset" don't behave the same:

element.style.border = ""; // This will simply have no effect on the border and border will stay whatever it was in CSS
element.style.border = "unset"; // In this case your border will not apply now and default value of the border will be set.

DEMO CODE:

document.querySelector(".test1").style.background = "";
document.querySelector(".test2").style.background="unset"; // It is set to the default value and no background color is applied
.test1,.test2{
  height:100px;
  width:100px;
  border:5px solid red;
  background:blue;
  margin-bottom:1rem;
}
<div class="test1">
</div>

<div class="test2">
</div>

The unset keyword resets a property to its inherited value if the property naturally inherits from its parent, and to its initial value if not inherited.

See here how the inherit keyword is working

I have taken color as the property instead of border for better understanding. Here you can check it live for better clarification

color: unset 

is same as setting 

color: inherit

inherit here takes the property of the parent element.

#element {
    border: unset; 
/*Here the border is inherits its parent property if it has a parent element */
}  

else if does not have parent inheritance it's same as setting

#element {
    /*nothing here!*/ 
  /*In this case you don't have parent inheritance and have default css*/
}

You can also check this codepens for better clarification: inherit property demonstration

Related