Search code examples
cssreactjsstyled-components

Can't get elements to stack


CSS isn't necessarily my strong suit but I have no idea why I can't get these two elements to stack? I set the parent position to relative and the child to absolute I also give the child a higher z-index but just can't get it to work. The <Icon /> is always offset to the right.

enter image description here

Code

import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';

const propTypes = {
  iconName: PropTypes.string,
  color: PropTypes.string,
};

const defaultProps = {
  iconName: 'add_box',
  color: '#27B678',
};

const MaterialIcon = props => (
  <i className={`material-icons ${props.className}`}>
    {props.iconName.replace(/['"]+/g, '')}
  </i>
);

const Icon = styled(MaterialIcon)`
  color: ${props => props.color.replace(/['"]+/g, '')};
  font-size: 36px;
  position: absolute;
  z-index: 10;
  top: 10%;
  left: 0;
  right: 0;
  bottom: 0;
`;

const Divider = props => (
  <div
    className="mx2"
    style={{ position: 'relative', border: '1px solid #ececec' }}
  >
    <Icon
      iconName={props.iconName}
      color={props.color}
    />
  </div>
);

Divider.propTypes = propTypes;

Divider.defaultProps = defaultProps;

export default Divider;

Solution

  • You need to use top and left to position the icon over the divider. You should give left a negative value equal to half the width of the icon so that it is centered over the divider. For instance, if the icon width is 50px, your Icon style should look like this:

    const Icon = styled(MaterialIcon)`
      color: ${props => props.color.replace(/['"]+/g, '')};
      font-size: 36px;
      position: absolute;
      z-index: 1;
      top: 10%;
      left: -25px;
    `;
    

    Make sure to also give your divider a z-index of 0 so that the Icon appears on top of it.