Login With Github

CSS Horizontal And Vertical Align

Document

In the CSS layout, you can set the horizontal and vertical alignment of the element, such as centering the text vertically and horizontally or centering the image horizontally.

Center the block element horizontally - Using the margin property

this is a centered paragraph.

A block element occupies a single line, and you can specify its width and height. You can get more information about block elements from here.

In order to center the block element horizontally, you first specify the width of the element, which prevents the element from overflowing outside the parent container.Then set the margin-left and margin-right property values to auto so that the margins on both sides of the element are equal.

Here is an example:

.center {
    margin-left: auto;
    margin-right: auto;
    width: 50%;
    border: 3px solid green;
    padding: 10px;
}

Note: If the width of the block element is 100%, it cannot be centered.

Note: Using margin:auto; is not valid in IE8 and earlier unless !DOCTYPE has been declared.

Align the text and images - Using the text-align property

this is a left-align paragraph.

this is a center-align paragraph.

this is a right-align paragraph.

You can align the text and images to left,right or center with the text-align property,for example:

.left {
    text-align: left;
    border: 3px solid green;
}
.right {
    text-align: right;
    border: 3px solid green;
}
.center {
    text-align: center;
    border: 3px solid green;
}

If the image is set as a block-level element, you cannot center it horizontally with text-align: center;.At this point you can place the image in a block element and set its left and right margins to auto, for example:

img {
    display: block;
    margin: 0 auto;
    width: 50%;
}

Center Vertically - Using the padding property

There are many ways to center an element vertically. The easiest way is to set the padding property of the parent container. For example:

this is a vertically centered paragraph.

.center {
    padding: 80px 0;
    border: 3px solid green;
}

If you want the element to be centered vertically and horizontally, you can use both the padding property and the text-align property. E.g:

this is a vertically centered and horizontally centered paragraph.

.center {
    padding: 80px 0;
    border: 3px solid green;
    text-align: center;
}

Center Vertically - Using the line-height property

You can also use the line-height property to center the element vertically, for example:

.center {
    line-height: 200px;
    height: 200px;
    border: 3px solid green;
    text-align: center;
}
 
/* If the text has multiple lines, add the following: */
.center p {
    line-height: 1.5;
    display: inline-block;
    vertical-align: middle;
}

Note: You must specify the height of the parent container.

0 Comment

temp