Neil
Neil

Reputation: 95

How to center elements vertically

so I have a component that needs to display a background image with a heading, some text and a button over it. However, all the elements seem to start way up in the page underneath my navbar. I can't seem to get them down to the middle of the div. I tried setting a margin-top to the 'main' div, that does bring the elements down but it also leaves a massive white space in between the components.

Main Section

return (
    <div className="main">
      <div className="container">
        <h1 className="main-heading">LOREM IPSUM</h1>
        <p>LOREM IPSUM SOME TEXT</p>
        <button>READ MORE</button>
      </div>
    </div>
  );

Main CSS:

.main {
  background-image: url("../../images/pharmacy.jpg");
  background-size: cover;
  z-index: -1;
  top: 10px;
  width: 100%;
  height: 600px;
  margin-top: 3rem;
}

.container {
  text-align: center;
  vertical-align: middle;
}
.main-heading {
  display: inline-block;
}

I also played around with styling the component in App.js with margin top like so:

      <main style={{ marginTop: "700px" }}>
        <MainSection />
      </main>

But it doesn't work. The text is basically underneath the component above.

EDIT: I've attached an image to show what's happening. I know a bit about styling and have tried the usual with flexbox. I'm not sure why they're stuck underneath the top component!

enter image description here

Upvotes: 0

Views: 41

Answers (1)

Quentin Grisel
Quentin Grisel

Reputation: 4987

You should use flexbox to vertially center your content, here is an example on Stackblitz and here is the code:

.js :import React, { Component } from "react";
import { render } from "react-dom";
import "./style.css";

const App = () => {
  return (
    <div className="container">
    Start editing to see some magic happen :)
    </div>
  );
};

render(<App />, document.getElementById("root"));

.css :

.container {
  height: 600px;
  display: flex;
  align-items: center;
  justify-content: center
}

Upvotes: 2

Related Questions