1

I'm doing an html and css course on udemy. The creator first said that the style tag must be placed in the head tag but then in one of the programs he put the style tag in the body tag and it worked. Could someone please explain this to me?

Aarya
  • 11
  • 2
  • 1
    Either works, though I think it's a bit more semantically appropriate to be in the `` – CertainPerformance Mar 24 '21 at 14:43
  • 1
    The general rule is that in order for the css to work, it must be placed before the relevant element – Alon Eitan Mar 24 '21 at 14:46
  • 2
    @AlonEitan — That isn't true at all. HTML requires the style element appear in the head. Error recovery in browsers can cope with it almost anywhere. There's no rules at all about the style element appearing before the element the CSS is applied to. – Quentin Mar 24 '21 at 14:48
  • ` – tacoshy Mar 24 '21 at 14:50
  • I really didn't know that CSS outside of the head is considered as invalid – Alon Eitan Mar 24 '21 at 14:51

2 Answers2

2

Browsers are very permissive and will often attempt to work with the html you provide, so technically both work. However the correct aproach would be to place it in the <head> quoting from https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style

The <style> element must be included inside the <head> of the document. In general, it is better to put your styles in external stylesheets and apply them using <link> elements.

fmsf
  • 36,317
  • 49
  • 147
  • 195
0

The short answer is: Yes you should always place the style tag under head. Placing it under body would still work most of the time, but is considered wrong or bad practice. If he put the style tag in body, he was doing the wrong thing.

If you are interested in a more detailed explanation as to why this is considered best practice, you can take a look at this thread: Does <STYLE> have to be in the <HEAD> of an HTML document?

Samson
  • 1,336
  • 2
  • 13
  • 28