HTML CSS Layout: How to center objects?

4:09 PM , , , 0 Comments

When we start building the layout of a website, we will always encounter a situation that we want to center an object in a layout. I summarize a few scenarios down here:


1. Horizontally center objects in div

1.1 Description
We will simply use an attribute in CSS: text-align. This method can be used to center texts, images, spans, etc, but not div.

1.2 CSS code:

.horizontal_center {
  text-align: center;
}


2. Vertically center one object in div

2.1 Description
To make the objects center vertically in a div, we will use another attribute in CSS: line-height. This method can only be used to center one line of text, if you have two separate lines of text, this method will not work. This also does not work for div, just for a line of text, an image or a span, etc.

We will use the height of div for the line-height.

2.2 CSS code:

.vertical_center {
  line-height: {div_height};
}


3. Horizontally center objects in div using margin-left, and margin-right.

3.1 Description
This method can be only used when the width of the object is fixed, like 100px.

3.2 CSS code:

.horizontal_center_using_margin {
  width: 100px;
  margin-left: auto;
  margin-right: auto;
}

4. Vertically center div in div

4.1 Description
We will use a wrapper div in this method.So you will finally have 3 div, the outer div one is using outer class; inside outer div, there is a wrapper div using wrapper class; inside wrapper div, there is inner div using inner class. The inner div will be vertically centered.

4.2 CSS code

.outer {
 width: 400px;
 height: 400px;
 background: #99cccc;
}

.wrapper {
 width: 400px;
 height: 400px;
 display: table-cell;
 vertical-align: middle;
}

.inner {
 width: 100%;
 height: 200px;
 background: #000000;
}

Unknown

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard.

0 comments: