How to center the div and its children on the page

Hi.

I am going through my 2nd Responsive Web Design project and I’m editing it on VS Code. At the, my h1 and p tags are rushed to the left of the browser. I want to center everything. I tried justifying the div to the center using the id but it didn’t work.

HTML:

<body>
    <div id="page-wrap">
        <h1>Survey Form</h1>

        <p>Please fill out the short survey</p>
    </div>
</body>

CSS:

#page-wrap {
    justify-content: center
}

are you trying to use flexbox? if so, you’d need to specify in your #page-wrap CSS

How do I go about doing that?

@omaroz92 You need to set display: flex in your container style rule.

I’ve added display: flex to the #page-wrap block but now justify-content: center is obsolete.

your ‘main’ container right now is the DIV #page-wrap. give it some dimensions (height /width) and maybe a border/background to visualize. Then give it some margins to move it around. Try ‘display:flex’ but it will default to Rows.

Inside that container are 2 children. give each the same (dimensions and a border/bgcolor). It really helped me learn better when I was moving around colored rectangles.

Box around a div did seem like a good idea so I made the following changes. I saw that I forgot the link tag so I was able to get the CSS to work with HTML - almost. While I was able to draw the border around div, I still can’t center h1 or p

HTML:

<!DOCTYPE html>
<html>

<link href="survey.css" rel="stylesheet" type="text/css"/>

<body>
    <div id="page-wrap">
        <h1>Survey Form</h1>

        <p>Please fill out the short survy</p>
    </div>
</body>
</html>

CSS:

#page-wrap {
    border: 1px solid black;
}

h1 {
    justify-content: center;
}

p {
    justify-content: center;
}

give #page-wrap: height, width, margins, background-color: red, display: flex, justify-content: center

h1: just height, width, margins, background-color: green

p: just height, width, margins, background-color:blue

you can text-align: center the h1 & p to center the text later, but get the containers laid out first.

For the div, what heights, widths and margins are appropriate? I want the height and the width to be the same as the browser. Also, display: flex renders justify-content: center null.

@omaroz92 Remember that h1 and p tags are inline elements by default. Using Flexbox your main box needs styles to control what properties it’s child boxes will have.


1 Like

Thank you very much. The game cleared it up a lot more.

you can use display property to its value flex. Default flex value is row, so change flex-direction property to column. it should work then.

    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
    text-align: center;
  }