Home > database >  div container will not center horizontally
div container will not center horizontally

Time:12-27

I'm doing a project on Frontend Mentor and it wants a layout for mobile and desktop.

I can not for the life of me get this to center horizontally. I've also noticed that when I switch to mobile view my body is smaller than the container it contains which may be some of the problem. I'm new to CSS and HTML so it's probably just something I'm missing.

Code can be found here - https://github.com/grizzle83/product-preview-card-component-main.git

Used Flexbox for mobile and grid for desktop just to get practice on both.

Expected justify-content/items and align-items to center this but it is not.

I can fix the body being being smaller than the container by adding position: absolute to the body element in css but this seems like a band-aid and not best practice.

CodePudding user response:

As you have not set a height to your container it has taken itself the minimum height required to fit all its child elements inside it. In order to expand the div across the screen provide it with a minimum height that matches the screen height.

So your .container code in your style.css must look like this.

.container {
  display: flex;
  flex-direction: column;
  width: 375px;
  justify-content: center;
  align-items: center;
  margin: auto;
  min-height: 100vh;
}

CodePudding user response:

You can wrap main and footer tag in a div and then apply the below CSS

body{
  display: flex;
  align-items: center;
  justify-content:center;
}

HTML should look like below: Wrapped main and footer in a Div tag

<body>
  <div>
    <main ></main>
    <footer></footer>
  </div>
</body>

CodePudding user response:

As I can see in your code, your element is not having full height, you can give specific height or just try below..

.container {
    min-height: 100vh;
}

  • Related