CodeBlanks Logo Icon CodeBlanks

Inline styles

Learn to write inline styles with the style attribute as an object.

Inline styles

An inline style is passed as an object to the style attribute: <div style={{color: "red"}}>. The double braces are easy to forget.

Because values are JavaScript, you write backgroundColor (camelCase), not background-color. Numbers are treated as pixels: padding: 8.

Inline styles are for quick prototypes; in big projects prefer CSS or Modules.

Dynamic styling

The power of inline styles is binding values to variables: style={{color: isError ? "red" : "green"}}. The color then changes with state.

You can do the same with className: className={isError ? "err" : "ok"}. Pick whichever is cleaner.

Inline styles do not support pseudo-classes (:hover); for those you need CSS.

Practice Dynamic colored box

Complete the skeleton. Write an AlertBox component; import useState. Define const [err, setErr] = useState(true);. Return <div style={{color: err ? "red" : "green"}}>Status</div>. Export it.

Starter code

App.jsx
import { useState } from "react";

// Define AlertBox here

Sample solution

App.jsx
import { useState } from "react";

function AlertBox() {
  const [err, setErr] = useState(true);
  return <div style={{ color: err ? "red" : "green" }}>Status</div>;
}

export default AlertBox;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How is background color written in inline styles?

App.jsx
CSS dashes become camelCase.
  • backgroundColor Correct answer
  • bgcolor
  • background-color
  • background

Explanation: JavaScript object keys use camelCase.

2 Inline styles: fill in the missing part

Question
<div style={{ ____: "red" }}>Note</div>
Answer
<div style={{ color: "red" }}>Note</div>

Explanation: The color key sets the text color.

3 Inline styles: match the terms

Term Meaning
style={{}} Inline object
backgroundColor camelCase
padding: 8 Pixel number
:hover Not inline

All lessons in Beginner