Languages
[Edit]
EN

React - how to move element to front using z-index CSS property

3 points
Created by:
DrJoystick
465

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).

z-index style property example in React.
z-index style property example in React.

Below example shows two components with different styles:

  • Component1 with zIndex: '1',
  • Component2 with zIndex: '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 or sticky.

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join