Home > Back-end >  How can you easily center a div when it comes to shapes?
How can you easily center a div when it comes to shapes?

Time:03-31

newbie here starting with the basics of HTML and CSS. I really have a hard time centering a simple div (a square in my example). I've watched many tutorials as well as read many articles but still cannot really figure out the "best" way to do it. With so many different ways like align-items, align-content, justify-items, justify-content, I get overwhelmed at some point especially with how these behave with different displays (flex, grid, inline-block etc), not to mention the positions of parents and childs. Below is an example that I still can't quite easily manipulate/center. The HTML is only the boilerplate and a blank div with class square inside the body. Thank you all in advance for your tips!

html {
  height: 100%;
}
body {
  min-height: 100%;
  background-color: #162944;
}
.square {
  height: 10rem;
  width: 10rem;
  background-color: salmon;
  display: flex;
  align-items:center;
  justify-items: center;
  align-content: center;
  justify-content:center;
  place-content: center;
  place-items: center;

}

The above example has been tried with all possible combinations and NOT only as you see it. Also with display:grid; and others. Is there really not a simple way to center an object on your page?

CodePudding user response:

One way to center a div is to set the width of the element and then use the margin property to set the left and right margins to auto. This will horizontally center the element within its container.

For example:

.element {
  width: 400px;
  margin-left: auto;
  margin-right: auto;
}

You can also by using the text-align property.

 .shape {
        text-align: center;
    }

Also by using the margin property.

For example:

.shape {
    margin: 0 auto;
}

Finally, you can center a div when it comes to shapes by using the transform property.

For example:

.shape {
    transform: translate(50%, 50%);
}

CodePudding user response:

Centering a div can be easy or hard based on your layout options and what you want to achieve.

The simplest way to horizontally center a div, add a width and margin: 0 auto.

Simplest way to horizontally and vertically center a div is using a flexbox, display: flex; justify-content:center; align-items:center. Also you can go with display:table and display:table-cell.

Last option is to use Positioning. You can take a div, style it with position:relative and add a height:300px,width:300px. Then inside the parent div, add a child div and style it with position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); height:50px; width:50px

  • Related