vanowm
vanowm

Reputation: 10201

Is there a way match background/text color for current theme?

When forcing a theme with color-scheme is there a way to match the actual text/background color? Background color Canvas and text color CanvasText don't quiet match the actual theme colors (in Edge/Chrome dark theme it shows as black color, while actual color is lighter) and when theme switched via javascript these colors don't reflect the changes (see "My Groupbox" label after clicking checkbox):

Math.floor(Math.random()*2)&&document.querySelector("input").click();
:root
{
  color-scheme: light;
}

.groupbox
{
  border: 1px solid rgba(127, 127, 127, 0.5);
  display: grid;
  padding: 1em 0.5em 0.5em 0.5em;
  position: relative;
  margin-top: 1em;
}

.groupbox > label
{
  position: absolute;
  top: -0.5em;
  left: 0.5em;
  font-size: 0.9em;
  padding: 0 0.4em;

  color: CanvasText;
  background-color: Canvas;
}
<label><input type="checkbox" oninput="documentElement.style.colorScheme=this.checked&&'dark'"> Dark theme</label>
<div class="groupbox">
  <label>My Groupbox</label>
  <h1>My Header</h1>
  <span>My Text</span>
</div>

Any suggestions?

Upvotes: 0

Views: 480

Answers (1)

tcanbolat
tcanbolat

Reputation: 411

The best solution I could find is changing the html elements to work better together and not using the Canvas & CanvasText css attributes. It seems like Canvas and CavasText won't change with the scheme and stick to their default colors.

Basically, I just replaced the wrapping <div> element with a <fieldset> and replaced <label> with <legend>, giving the same exact result but now you don't have to worry about the background or text color. It also allowed me to remove some css that was no longer needed.

the <fieldset> & <legend> work well together and you don't have to worry about the border line crossing through your text like it was doing with the <div> & <label> element.

Math.floor(Math.random() * 2) && document.querySelector("input").click();
:root {
  color-scheme: light;
}

.groupbox {
  border: 1px solid rgba(127, 127, 127, 0.5);
  padding: 0.5em 0.5em 0.5em 0.5em;
  position: relative;
  margin-top: 1em;
}
<label><input type="checkbox" oninput="documentElement.style.colorScheme=this.checked&&'dark'"> Dark theme</label>
<fieldset class="groupbox">
  <legend>My GroupBox</legend>
  <h1>My Header</h1>
  <span>My Text</span>
</fieldset>

Upvotes: 1

Related Questions