9

Is it possible to inline a class definition of CSS inside an xhtml file?

I mean, to put someting like:

p.first{ color: blue; }
p.second{ color: red; }

Inside my page, not in a separate CSS file.

home
  • 12,468
  • 5
  • 46
  • 54
Mr.Eddart
  • 10,050
  • 13
  • 49
  • 77

5 Answers5

20

I think you're trying to put your CSS in the HTML page, not inline.

You can put CSS in an HTML page (usually in the head) by surrounding it in style tags:

<style type="text/css">
    p.first{ color: blue; }
    p.second{ color: red; }
</style>
Joe
  • 15,669
  • 4
  • 48
  • 83
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
  • 2
    The question is tagged XHTML, not HTML5 though ;-) – Joe Sep 15 '11 at 17:20
  • 1
    @Joe: the question was originally tagged JSF, which uses a XML based view technology (Facelets) which requires XHTML templates to generate HTML. The output can be as good perfectly valid HTML5. See also http://stackoverflow.com/questions/2935759/is-it-possible-to-use-jsffacelets-with-html-4-5/3869174#3869174 – BalusC Sep 15 '11 at 17:30
4

Sure, here's an example. However, it is best practice to keep your styles in a separate css file.

<html>
    <head>
        <title>Classes</title>
        <link rel="stylesheet" type="text/css" href="css/styles.css"/>    
        <style type="text/css">
         img {
             padding:10px;
             margin:5px;
             border:1px solid #d5d5d5;
          }
          div.thumb {
             float:left;
          }
          div.caption {
             padding-left:5px;
             font-size:10px;
          }
       </style>
     </head>
    <body>
        <div>your page code etc..</div>
    </body>
</html>
FAtBalloon
  • 4,500
  • 1
  • 25
  • 33
3

You can also put css inside the p tag.

<html>
<body>
<p class="first" style="color:blue;"></p>
<p class="second" style="color:red;"></p>                                               
</body>
</html> 
shridhar
  • 35
  • 1
  • 4
2

The nice thing about CSS is it works in any file not just an HTML,XML file. You just need to define the syle block like this anywhere in the page

<style type="text/css">
    <all my styles goes here>
</style>

In HTML and HTML/XHTML, the standard is, you will put this block in the head section. If it is other type of file for example .aspx, or .php, the block still works, even it is not in head block.

Example

<?php
 /* mytest.php file */
<style>
   <my styles>
</style>

?>

the same is true for ASPX file.

You can also define inline CSS which means CSS goes right in the element tag. The syntax is

<p style="<all my styles>"> My paragraph contain inline CSS</p>
TheTechGuy
  • 16,560
  • 16
  • 115
  • 136
1

Yes, you can insert CSS styles in the HTML file. For example:

<p>...</p>
<style type="text/css">
p.first { ... }
</style>
<div>...</div>

As you'll find in the literature, it's not considered a good practice though.

moey
  • 10,587
  • 25
  • 68
  • 112