Home > Net >  Why is the style of body not applied?
Why is the style of body not applied?

Time:08-22

My HTML:

function ReverseString(Text) {
  var ReturnValue = "";
  for (var i = (Text.length - 1); i >= 0; i--) {
    ReturnValue  = Text.at(i);
  }
  return ReturnValue;
}

function ReverseUserInput() {
  var Input = document.forms[0].elements[0].value;
  document.forms[0].elements[0].value = ReverseString(Input);
}
body {
  font-size: 14px;
}
<form>
  <textarea rows="4" cols="26" class=gross>Text</textarea>
  <input type="button" value="Reverse" onClick="ReverseUserInput()">
</form>

I apply CSS to body, but the CSS for body will not be applied. Could somebody please explain why?

CodePudding user response:

By default, on most browsers form fields don't inherit their font settings from their parent like other elements do. To make them do that, you can use inherit for their font-size, etc. For instance, to apply an inherited font size to textarea, button, input, and select elements:

textarea, button, input, select {
    font-size: inherit;
}

Updated snippet:

function ReverseString(Text) {
  var ReturnValue = "";
  for (var i = (Text.length - 1); i >= 0; i--) {
    ReturnValue  = Text.at(i);
  }
  return ReturnValue;
}

function ReverseUserInput() {
  var Input = document.forms[0].elements[0].value;
  document.forms[0].elements[0].value = ReverseString(Input);
}
body {
  font-size: 14px;
}
textarea, button, input, select {
  font-size: inherit;
}
<form>
  <textarea rows="4" cols="26" class=gross>Text</textarea>
  <input type="button" value="Reverse" onClick="ReverseUserInput()">
</form>

Or of course, explicitly set their font-size, perhaps in the same rule as the one you set for body:

body, textarea, button, input, select {
    font-size: 14px;
}

CodePudding user response:

None of the text nodes in your document are children of either the body or children of an element influenced by the body's font size (e.g. with font-size: inherit or font-size: 1em).

textarea and input elements (the only elements in your document with text inside them) have explicit default font-sizes from the browser style stylesheet that you haven't overridden.

So it is applied. There is just nothing in the document that it affects.

Compare to this example where textarea and input have relative font-sizes set.

body {
  font-size: 14px;
}

textarea,
input {
  font-size: 1em;
}
<form>
  <textarea rows="4" cols="26" class=gross>Text</textarea>
  <input type="button" value="Reverse">
</form>

  • Related