Yu-Chieh’s Blog (Y.C. Chang)

Ruby on Rails / Rubygems / FullStack / Git / Mac notes.

How to Put Css in Html Body?

  • There are two ways to set css file into our html documents.
  • first way: using pure javascript to append css file into head part of html.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script type="text/javascript">

   function loadCSS(filename){

      var file = document.createElement("link")
      file.setAttribute("rel", "stylesheet")
      file.setAttribute("type", "text/css")
      file.setAttribute("href", filename)

      if (typeof file !== "undefined")
         document.getElementsByTagName("head")[0].appendChild(file)
   }


  //just call a function to load a new CSS:
  loadCSS("path_to_css/file.css")

</script>
  • Or we can simply use jquery.
1
$('head').append('<link rel="stylesheet" type="text/css" href="{yoururl}">');
  • Fashion way is to use style tag in body. (notice: some old browsers would not support this.)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html>
<head></head>
<body>

<div id = "scoped-content">
    <style type = "text/css" scoped>
    h1 { color: red; }
    </style>

    <h1>Hello</h1>
</div>

<h1>World</h1>

</body>
</html>

references: - http://stackoverflow.com/questions/11833325/css-hack-adding-css-in-the-body-of-a-website - http://stackoverflow.com/questions/2830296/using-style-tags-in-the-body-with-other-html - http://html5doctor.com/the-scoped-attribute/

Comments