user3479074
user3479074

Reputation: 131

CSS: set border-color to parent's background-color

assume the following snippet.

.parent {
  width: 300px;
  height: 300px;
  background-color: grey;
  display: flex;
}

.child {
  width: 50%;
  height: 50%;
  background: white;
  margin: auto;
  border: 5px dotted grey;
}

.parent:hover {
  background-color: darkcyan;
}

.parent:hover>.child {
  border-color: darkcyan;
}
<div class="parent">
  <div class="child"></div>
</div>

Note that the child-div has a border which has the same color like the parent-div. When hovering parent-div, its background-color changes while the border-color (actually I'm using -webkit-text-stroke) of the child-div changes to the same color.

Instead of setting the child's border-color manually, I actually want the child to always use its parent background-color. This behaviour is easy to implement when both elements are using the same property by simply inheriting it. Is there any way to achive this behaviour using different properties?

Thanks

Upvotes: 7

Views: 14997

Answers (2)

tequilacat
tequilacat

Reputation: 757

You can use CSS custom properties aka variables - they are inherited by children and can be used for any property.

https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties

Define them in parent, and then you can reuse them in parent and child class:

.parent {
  --parent-mainfill: grey;
  --parent-hoverfill: darkcyan;
 
  width: 300px;
  height: 300px;
  background-color: var(--parent-mainfill);
  display: flex;
}

.child {
  width: 50%;
  height: 50%;
  background: white;
  margin: auto;
  border: 5px dotted var(--parent-mainfill);
}

.parent:hover {
  background-color: var(--parent-hoverfill);
}

.parent:hover>.child {
  border-color: var(--parent-hoverfill);
}
<div class="parent">
  <div class="child"></div>
</div>

Upvotes: 1

Mohammad Usman
Mohammad Usman

Reputation: 39392

You can use border-color: transparent

.parent:hover > .child {
  border-color: transparent;
}

This will allow you to change background of parent only without overriding child's border-color each time.

Don't forget to set child's background-clip to padding-box so that background covers only the content area excluding border.

* {box-sizing: border-box;}
.parent {
  width: 300px;
  height: 300px;
  background-color: grey;
  display: flex;
}

.child {
  width: 50%;
  height: 50%;
  background: white;
  background-clip: padding-box;
  margin: auto;
  border: 5px solid grey;
}

.parent:hover {
  background-color: darkcyan;
}

.parent:hover>.child {
  border-color: transparent;
}
<div class="parent">
  <div class="child"></div>
</div>

Upvotes: 11

Related Questions