Search code examples
htmlcssreactjsfrontendstyled-components

How should I style this img element to achieve the effect I want


https://codesandbox.io/s/relaxed-margulis-rr9zo

Guys this is the code I have so far. Pretend the chrome logo is the photo of a person. enter image description here

I need the photo to be side by side of the name and subtitle. And when you narrow your browser, the logo will get closer to the text and the logo will be under the text. I used styled-component and the style I wrote for the logo are

const ImgCotainer = styled.img`
  position: relative;
  top: -300px;
  z-index: -1;
`;

However, what I achieved so far has two major problems.

First is, I am not really good at CSS. I cannot really position the logo well(as you can see in the demo)

Second, I set the z-index: -1; to make it below the text. But weirdly it takes roughly 1 sec to make that overlap happen. You will get what I mean when you see the demo.

I know my question might be trivial to someone who have lots of experience with css but I really appreciate any help.

Finally, the look I aim to achieve is something like this. I feel like the photo is more likely to be a stand alone img rather than the background-image of the whole thing. And I tried to find the source code for websites like this and learn how they did it and the animation related to it but I just couldn't find it. enter image description here


Solution

  • Solution 1:

    You can set width of the image to change with respect to viewport width and also set the desired max-width of the image for larger screens.

    Set display to block and left and right margin to auto to display your image in the center horizontally.

    const ImgCotainer = styled.img`
      position: relative;
      top: -300px;
      z-index: -1;
      width: 50vw;
      max-width: 400px;
      display: block;
      margin: 0 auto;
    `;
    

    Here is a sample image you can use.

    const img = () => (
        <div style={{ transitionDelay: "600ms"}}>
          <ImgCotainer src="https://pngimg.com/uploads/doctor/doctor_PNG16036.png" />
        </div>
    );
    

    Solution 2:

    Setting positioning and z-index to the image container's parent element will solve your problem of image animating in front of the text and then animating under the text after a few seconds.

    const img = () => (
        <div style={{ 
          transitionDelay: "600ms",
          position: "absolute",
          bottom: 0,
          display: "flex",
          zIndex: -1,
          justifyContent: "center" 
        }}>
          <ImgCotainer src="https://pngimg.com/uploads/doctor/doctor_PNG16036.png" />
        </div>
     );
    

    In this case your image container can be very simple.

    const ImgCotainer = styled.img`
       width: 80vw;
       max-width:  700px;
    `;
    

    Check the following implementation:

    Sandbox

    Demo