How To Center Elements with HTML and CSS

Fort Lauderdale Web Design

23

Mar

There are a number of ways you can center an element using CSS and HTML depending on the type of element and the requirements for that element. First, let’s assume we want to center a div inside of a wrapper div or in the middle of the document body.

Whether our div, with a class “center-div”, is directly inside the body tag or a wrapper div we’ll first need to assign a width. This width can be static, or a fixed pixel value, or it can be dynamic, or set with a percentage. As responsive design is very popular, let’s use the dynamic width of 80% and put it directly inside the body tag. So far our code looks like this.

<code>
<style>
.center-div {
width:80%;
}
</style>

<body>
<div>
Some Text
</div>
</body>
</code>

Now to center the div we have to apply a margin to every side of our center div. To the top and bottom it can be any value from 0 to infinity depending on your top margin needs, but both left and right margins must be set to ‘auto’. So now our code looks like this.

<style>
.center-div {
width:80%;
margin:0 auto;
}
</style>
<div>Some Text</div>

Now to ensure the centered div displays properly I usually add the following CSS properties: overflow:hidden;, display:block;, min-height:250px. You can use different settings for the display and min-height, or skip them all together, but overflow:hidden is a very useful property that often goes underused. Your final code should look like this:

<style>
.center-div { width:80%; margin:0 auto; overflow:hidden; display:block; min-height:250px; }
</style>&nbsp;
<div>Some Text</div>

Once done, the div you need centered should be directly in the middle of its container div horizontally. You can also center the text within that div by giving the text tag a text-align:center property.

BricksMortarCreative on DesignQuote

Web Design

CALL US NOW