Thursday, March 21, 2019

HTML: style and class


HTML inline styles can be replaced by using CSS class. For example, the following code:

<p id="p1" style="font-size:100px; color:blue;">Big blue</p>

can be rewritten into

<p id="p2" class="bigblue">Big blue</p>

by using a "bigblue" class defined in a linked CSS file:

.bigblue {
  font-size:100px;
  color:blue;
}


There is something we need to pay attention to if we want to dynamically hide and show an element with the style.display property. For example, if we want to hide the above "p1" element initially and later show it, we can do this with inline style:

<p id="p1" style="font-size:100px; color:blue; display:none;">Big blue</p>

<script type="text/javascript">
  // Later, we remove the style.display property to show the element.
  document.getElementById("p1").style.display = "";
</script>


However, for the other approach with CSS class, resetting style.display doesn't work:

.bigblue {
  font-size:100px;
  color:blue;
  display:none;
}


<p id="p2" class="bigblue">Big blue</p>

<script type="text/javascript">
  document.getElementById("p2").style.display = "";   // "p2" won't show up
</script>


We would need to explicitly set the style.display to its default value "inline" to make the element show up:

<script type="text/javascript">
  document.getElementById("p2").style.display = "inline";  

</script>

No comments:

 
Get This <