Search code examples
javascriptcssreactjsstyled-components

Can't get styled components to center logo in center of screen?


I am not sure if it's with the component structure or what if somebody could explain that this is only like my 2nd week using react, and second time using styled components.

Sorry if this is something simple.. I was looking at this code pen which is basically what I am trying to achieve.. Codepen

Here is the file :

Home.js -

import React from 'react'
import styled from "styled-components";
import Background from './images/Cryptid.png'
import { createGlobalStyle } from 'styled-components'


const Home = () => {

    return (

        <Container>
            <GlobalStyle />
            <InnerContainer>
                <Logo />
                <JoinInfo><p>test</p></JoinInfo>
            </InnerContainer>
        </Container>
    )


}

const GlobalStyle = createGlobalStyle`
  body {
    background: black;
  }`


const OutterContainer = styled.div`
display: flex;
height: 100%;
width: 100%;
`;

const Container = styled.div`
height: 100%;
width: 100%;
`;

const InnerContainer = styled.div`

height: 100%;
width: 100%;
`;

const Logo = styled.div`
justify-content:center;
align-items:center;
border: 1px solid red;
/* margin: auto;
padding: auto; */
height: 100px;
width: 400px;
background-image: url(${ Background});
`

const JoinInfo = styled.section`

  align-items: center;
  justify-content: center;
color: white;
`
export default Home;

Solution

  • justify-content and align-items are the correct properties however they should be placed on the container and they will be applied to the children.

    Let's create a container to wrap the logo in. We'll use the flex properties and some others.

    const LogoContainer = styled.div`
    display: flex;
    justify-content:center; // centers in the flex direction and the default flex-direction is row
    align-items:center; // centers perpendicular to the flex direction
    height: 100vh; // 100% view height
    width: 100vw; // 100% view width
    position: absolute; // so it goes behind the current content
    `;
    
    

    You can learn more about css flexbox at MDN.