Free Web Development Online Tutorials, Learn to Code
CSS align attribute, CSS Align Content, align Text Image

CSS Align Attribute

In this tutorial you will learn how to align things in CSS, like align Image, align Text, align content etc, alignment can be Vertical and horizontal

How To Align Things In CSS

As I mentioned before, alignment can be Vertical and horizontal, and for each alignment there are different values, let us learn with example.

horizontal align example

When we do not specify any alignment type, it is considered as horizontal alignment. Like in align text example below, the text will be aligned horizontally center.

.ex1 {
    text-align: center;       
}

There are different values for text align property, like text-align: left | right | justify | match-parent;

You can use the same above css for align image center, you need to write the css align property in parent container. , then all content inside that container will be center aligned.

<div style="width: 100%; padding: 10px; text-align: center;">
    <img src="~/images/learn-css.png">
</div>

css align div in center of another div

If you want to bring a div in center of another div, use margin: auto 0;

Parent Div
Child Div
<div style="width:100%;background-color:#0094ff;padding:10px;">
Parent Div
<div style="width:50%;background-color:#ff0000;padding:10px;margin:0 auto;">Child Div</div>
</div>

Vertical Alignment

now we see how to write css to align elements in div vertically

if we don’t define anything for vertical alignment, then child div will be vertically top aligned by default inside a parent div.

So, to bring the child div vertically middle, you need to use some css tricks, unfortunately vertical-align:middle does not work.

One simplest way can be setting top-padding of child div, it can force the child div to appear almost in middle, but really not a good idea.

Another way would be using multiple properties like vertical-align: middle; display: table-cell; and for child div margin: 0 auto; display: inline-block;

.parentDiv1 {
    width: 100%;
    background-color: #0094ff;
    padding: 10px;
    height: 300px;
    vertical-align: middle;
    display: table-cell;
}

.childDiv1 {
    width: 50%;
    background-color: #ff0000;
    padding: 10px;
    margin: 0 auto;
    display: inline-block;
}
Parent Div
Child Div - Vertically middle

Alignment

 
CSS align attribute, CSS Align Image, Text, Vertical and horizontal align

digital marketing software


CSS Style Examples