How to make a box in HTML CSS

You can make a box in HTML CSS using a couple of ways. Such as border, background-color, etc. In this post, I will create different types of boxes using only CSS (and HTML).

Make a box using the CSS border (Example# 1)

In this example, I will create a box for an empty div (class). See the final output below:

For the above box, I have an empty div with a class of “box.”

<div class="box"></div>

And I wrote the following CSS to create the box:

.box {
  width: 400px;
  height: 300px;
  border: 2px solid #222;
  margin: 10px auto;

I took a fixed width and height but you can replace these values to meet your unique needs. Additionally, I have auto margin from the left and right directions to make the box center aligned.

Create a box using CSS background-color (Example# 2)

Before I explain the CSS, see the final output first:

In this example, I have the following HTML and CSS:

<div class="box-outer">
	<div class="box-inner"></div>
.box-outer {
  background-color: #222;
  width: 400px;
  height: 400px;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  margin: 10px;
.box-outer .box-inner {
  background-color: #FFFFFF;
  width: 396px;
  height: 396px;

That means I have a semi-black (#222) background-color for the first wrapper div (.box-outer). It has a 400px width and height.

And in this semi-black space, I also have taken another div that is 396px in width & height. Because my aim is to create a 2px border surrounding the box.

As you can see that I used the flex box in this example. The justify-content: center; will make the second box horizontally centered according to the first box. And the align-items: center; will do the same for vertical alignment.

Learn more about centering vertically with flexbox.

Not to mention, in this example, the above box is left aligned. But if you want to make it center aligned, you have to wrap these two divs within another container div. And align (center) the container div as I did in this example.

The best approach to make a box using the CSS border property. It also depends on the context and where you need to create the box. However, the content, margin, padding, and border may make changes to the box. To learn more see how the box model.