Thursday, June 1, 2017

Css for centering elements



There is no option to float center. However by thinking carefully about how elements behave, we can use positioning to achieve the same result

Center horizontally

we can center the element by specifying margin : 0 auto. This would make sure that it would be perfectly centered horizontally. This is telling the browser to move left and right in equal amounts (Would have equal amount of margin to the left and right).This would have a effect of centering it perfectly in the page

Note :
The values for the top and bottom could be anything and we would get the same result
we need to have to set width for the div. If not it would take the full width

Link to GitHub :Code



Css
.box{
    width:200px;
    height:200px;
    border-bottom:1px solid #eee;
    background-color: lightgrey
}
.horizontalAlign{
    margin:0 auto;
}

html

<div class="floatRight">
    Float Right
</div>
<h1>We can float  </h1>
<div class="box horizontalAlign">
    <strong>Horizontal align</strong>
</div>

Center vertically

  • We need to set the position : absolute as it would remove it from the document model
  • We would move form the top :50% ( Would be centered with the imaginary line
  • We need to set the margin-top to half of our container margin-top: -50px

css

.box{
    width:200px;
    height:200px;
    border-bottom:1px solid #eee;
    background-color: lightgrey
}
.verticalAlign{
    position:absolute;
    width:200px;
    top:50%;
}

 html
<div class="floatRight">
    Float Right
</div>
<h1>We can float  </h1>

<div class="box verticalAlign">
    <strong>Vertical align</strong>
</div>

Center horizontally and vertically 

Link to GitHub: Code
 We need to move the vertical properties to the container Add left :0 and set width of the container to width:100% Now we need to set it to center horizontally margin : 0 auto

No comments:

Post a Comment