In this tutorial you will learn how to align things using CSS Style, like align Image, align Text, align content etc, alignment can be Vertical and horizontal
style="text-align:center;" style="vertical-align:middle;"
As I mentioned before, alignment can be Vertical and horizontal, and for each alignment there are different values, let us learn with 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>
If you want to align a div in center of another div, use margin: auto 0;
<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>
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; }
Setting alignment rightly using css style sheet will help you design responsive webpage.