Search code examples
cssreactjsstyled-components

How to position a div outside other div?


I'm trying to position a div with an image outside my main Card component. I have tried using margin-bottom, however, it didn't work. How can it be done using CSS styled-component?

I will attach an image here of the design that I'm trying to achieve:] https://i.sstatic.net/9RT3a.jpg

Card Component:

function CardComponent(props) {
  return (
    <>
      <Card>
        <CardImage>{props.img}</CardImage>
        <CardName>{props.name}</CardName>
        <Description>{props.description}</Description>
        <Links>
          <Button>{props.livePreview}</Button>
          <Button>{props.github}</Button>
        </Links>
      </Card>
    </>
  );
}

export default CardComponent;

Styled Component

import styled from "styled-components";

export const Card = styled.div`
  width: 25%;
  height: 70vh;
  border: 1px dotted black;
  margin-top: 5%;

  @media (max-width: 768px) {
    width: 100%;
  }
`;

export const CardImage = styled.div`
  border: 1px solid pink;
  width: 80%;
  height: 50vh;
  margin: auto;
`;

export const CardName = styled.div`
  border: 1px solid black;
  text-align: center;
`;

export const Description = styled.div`
  text-align: center;
`;

export const Links = styled.div`
  display: flex;
  border: 1px solid pink;
  justify-content: center;
`;

export const Button = styled.div`
  border: 1px solid blue;
`;


Solution

  • You can use either position: absolute or margin-top to achieve it. Check the snippet attached:

    section {
      padding: 10px;
      border: 1px solid #ddd;
      text-align: center;
      display: inline-block;
      max-width: 300px;
      margin-top: 50px;
    }
    
    img {
      max-width: 80%;
      margin-top: -30px;
    }
    <section>
      <img src="https://media1.popsugar-assets.com/files/thumbor/_Rrjw5u5qeqlO8Zznc0TskZB_8k/fit-in/1024x1024/filters:format_auto-!!-:strip_icc-!!-/2018/04/30/868/n/1922283/1f2e59ed5ae773b06f2879.82877284_/i/Does-Iron-Man-Die-Avengers-Infinity-War.jpg" />
      <h4>Hello world</h4>
    </section>