Prev Page Next Page
Top

CSS Align

➢To horizontally center a block element (like <div>), use margin: auto;
➢Setting the width of the element will prevent it from stretching out to the edges of its container.
➢The element will then take up the specified width, and the remaining space will be split equally between the two margins:

EXAMPLE:

div {
     margin: auto;
     width: 50%;
     border: 3px solid green;
     padding: 10px;

}

RESULT:

The div element is centered

Run


➢To just center the text inside an element, use text-align: center;

EXAMPLE:

div {
     margin: auto;
     width: 50%;
     border: 3px solid green;
     padding: 10px;
     text-align: center;

}

RESULT:

The text is centered

Run


➢There are many ways to center an element vertically in CSS. A simple solution is to use top and bottom padding:

EXAMPLE:

div {
     border: 3px solid green;
     padding: 70px;

}

RESULT:

I am vertically centered.

Run


➢Another trick is to use the line-height property with a value that is equal to the height property:

EXAMPLE:

div {
     line-height: 200px;
     height: 200px;
     border: 3px solid green;
     text-align: center;

}

div p {
     line-height: 1.5;
     display: inline-block;
     vertical-align: middle;

}

RESULT:

I am vertically and horizontally centered.

Run


➢If padding and line-height are not options, another solution is to use positioning and the transform property:

EXAMPLE:

div {
     height: 200px;
     border: 3px solid green;
     position: relative;

}

div p {
     margin: 0;
     position: absolute;
     top: 50%;
     left: 50%;
     transform: translate(-50%, -50%);

}

RESULT:

I am vertically and horizontally centered.

Run


Prev Page Next Page





FEEDBACK