Tuesday, 15 September 2015

html - what does the negative margin do to set the element in the center of the page? -



html - what does the negative margin do to set the element in the center of the page? -

i came across next css snippet. gives element id search bar absolute position,a width of 300px,height of 27px , sets search bar 50% it's normal position

#search_bar { position:relative; width: 300px; left:50%; height:27px; }

but don't see search bar aligned in center. why ? if alter snippet :

#search_bar { position:relative; width: 300px; margin-left:-150px; left:50%; height:27px; }

it gets aligned center of page. how ? property margin-left:-150px set center ?

it because using position absolute negative margin half of width of element shifts element behind 1/2 of it's total width

position: absolute; left: 50%; /* shifts element 50% left, if don't want utilize negative margins can utilize 45%, 40% need fiddle measurements first */

so calculation goes like

total container width 1000px

element width 300px

left: 50% means start left 500px 800px

so not centered yea?

so -150px 500px /* 500 here left: 50% */

you element 350px 650px

html css

No comments:

Post a Comment