You can use this property to set the element horizontally or vertically center
This is horizontally center due to margin auto
This property run in IE8 only if you mention !DOCTYPE otherwise not apply
<style>
#center {
border: 3px groove blue;
margin: auto;
width: 50%;
padding: 15px;
}
</style>
<h2> Elements Align Center</h2>
<p>This is horizontally center due to margin auto</b>
</p>
<div id="center">
<p>This property run in IE8 only if you mention !DOCTYPE otherwise not apply</p>
</div>
<style>
#center {
border: 3px groove blue;
margin: auto;
width: 50%;
padding: 15px;
text-align: center;
}
</style>
<h2> Text Align Center</h2>
<div id="center">
This text is center by <b>text-align</b> property.
</div>
You can center the image by setting margin auto of left and right side of image and dispaly as block.
<style>
img {
display: block;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body><h2>Image as center</h2>
<img src='https://codingpk.com/images/natural.jpg' title='natural' alt='natural' />
<style>
.left {
position: absolute;
width: 250px;
border: 1px solid #00FFFF;
padding: 15px;
}
</style>
<div class="left">
<p>This div is align left with position absolute property</p>
</div>
<style>
.left {
border: 4px solid #8A2BE2;
float: left;
width: 350px;
padding: 15px;
}
</style>
</head>
<body>
<h2>Align Left</h2>
<div class="left">
This div is align left through float property.
</div>
If inner element(such as image) of main element(such as div) can overflow from the container then this issue can solve by adding overflow: auto property to an imagfix class.
<style >
.notfix{
border: 4px solid #008000;
margin-bottom: 150px;
padding: 5px;
}
.img1 {
float: right;
}
.imagfix {
border: 4px groove #008000;
overflow: auto;
padding: 5px;
}
.img2 {
float: right;
}
</style>
<div class="notfix">
You can see that image can overflow from div.
<img src='https://codingpk.com/images/apple.jpg' title='apple' alt='apple' width= "150px" height="100px"/>
</div>
<div class="imagfix ">
Above problem is resolve through <b>overflow: auto;</b>property.
<img class="img2" style="float: right;" src="apple.jpg" width= "150px" height="150px">
</div>
This text is vertically centered.
<head>
<style>
#vercenter {
padding: 50px 5px;
border: 2px solid purple;
}
</style>
</head>
<body>
<p> we use padding property to vertical center the paragraph </p>
<div id="vercenter">
<p>This text is vertically centered.</p>
</div>
</body>
</html>
This text is vertically and horizontally centered.
<style>
#vhcenter {
padding: 50px 5px;
text-align: center;
border: 2px solid purple;
}
</style>
<body>
<p> Add text align and padding property to centered the element horizontally and vertically </p>
<div id="vhcenter">
<p>This text is vertically and horizontally centered.</p>
</div>
</body>