Show and Edit Style Element

Avatar of Chris Coyier
Chris Coyier on (Updated on )

DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!

Kind of a classic little trick for ya’ll today. You know the <style> blocks you can put in the <head> of your HTML to do styling? You don’t actually have to put those in your head, they can be anywhere on the page.

What’s more? It’s just an element like any other. The default stylesheet of all browers makes it display: none;.

If you move it down into the body and reset it to display: block; you can see the very code which is applying style to that page. Might as well make it look nice and code-y to eh?

body style {
	display: block;
	background: #333;
	color: white;
	font: 13px/1.8 Monaco, Mono-Space;
	padding: 20px;
	white-space: pre;

What’s more? You can give it the HTML5 attribute of contenteditable and you can literally edit the CSS right there and watch it effect the page.

<style scoped contenteditable>body { 
  background: green; 

View Demo

That’s how all the code on The Shapes of CSS page is done. Not only is it just kinda neat, but it’s very useful on a page like that so you don’t have to maintain the CSS in two places.

I don’t think it’s a very good practice in general, outside of CSS demos. <style> blocks in general I’d go so far as to say are bad practice unless it’s a really specific third-party scenario like where injecting styles is the most efficient way to styling newly injected third-party content.

Also for the record, it’s not invalid to use <style> outside of the <head> as long as you use the scoped attribute and it’s the first child of it’s parent. Otherwise it is invalid. The scoped attribute (although currently supported in no browsers) is supposed to imply that the styles within only apply to that parent element and nowhere else. Learn more about it.