Inline Styles
4 minutes of reading
In React, each HTML element has an attribute called style which accepts a JavaScript object. You can specify CSS style property names and values as keys and values in this object.
<div
style={{
height: "30px",
"background-color": "grey",
}}
>
Koala
</div>
Unlike normal CSS, you can use the camel case to specify a property name if it contains more than one word.
<div
style={{
height: "30px",
backgroundColor: "grey",
}}
>
Koala
</div>
You can apply inline styles conditionally.
<div style={{ color: !isValid ? "red" : "back" }}>Question 1</div>
Vendor prefixes other than ms should begin with a capital letter. This is why WebkitTransition has an uppercase W.
const KoalaTransformer = (props) => {
const koalaStyle = {
WebkitTransition: 'all',
msTransition: 'all'
}
return <div style={koalaStyle}>This should work cross-browser</div>;
};
React will automatically append a “px” suffix to certain numeric inline style properties. If you want to use units other than “px”, specify the value as a string with the desired unit.
// Result style: '10px'
<div style={{ height: 10}}>Hello Koalas!</div>
// Result style: '10%'
<div style={{ height: '10%'}}>Hello Koalas!</div>