EN
React - how to move element to front using z-index CSS property
3
points
In this article we would like to show you how to move element to front using zIndex
style property (z-index
property equivalent in pure CSS).
Below example shows two components with different styles:
Component1
withzIndex: '1'
,Component2
withzIndex: '2'
.
An element with greater zIndex
is always in front of an element with a lower zIndex
value, so in our case Component2
(zIndex: '2'
) covers Component1
(zIndex: '1'
).
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines in you project.
// import React from react';
// import ReactDOM from 'react-dom';
const Component1 = () => {
const style = {
position: 'absolute', // <------ required
left: '30px', // <------ also may be required
top: '10px', // <------ also may be required
background: 'goldenrod',
width: '100px',
height: '100px',
zIndex: '1' // <------ required
};
return (
<div style={style}>
z-index: 1
</div>
);
};
const Component2 = () => {
const style = {
position: 'absolute', // <------ required
left: '10px', // <------ also may be required
top: '40px', // <------ also may be required
background: 'yellow',
width: '100px',
height: '100px',
zIndex: '2' // <------ required
};
return (
<div style={style}>
z-index: 2
</div>
);
};
const App = () => {
const style = {
height: '120px'
};
return (
<div style={style}>
<Component2 /> {/* <------ will be displayed over component 1 */}
<Component1 /> {/* <------ will be displayed under component 2 */}
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);
Note:
zIndex
only works when element has position set to:fixed
,absolute
,relative
orsticky
.