Not sure what I am getting wrong here, but let’s say I have two divs, and an h1 element (or P1) for that matter that looks like this:
<div class="wrapper">
<div class="top">
<h1>Content header</h1>
</div>
</div>
I want my element to appear in the ‘center middle’ of the inner div, that is it’s immediate parent. To achieve this, I give it a margin-top:50% & a margin-left:50% with the understanding that this would render it exactly towards the center middle of the div. But while it does get it to the middle, it doesn’t quite get it to the center. Infact it seems to position itself relative to the outer div, the one with class wrapper.
I have recreated this using jsfiddle here:
Am I specifying the selectors wrong or is my positioning in itself incorrect?
-the above ans isnt completely correct as the text will still not be completely centered vertically.
explanation:
-ever element in
htmlis in the form of a rectangular box so applyingmargin-top:50%is aligning the top of that box to 50% of the parent element and not the text inside the box.-that is the reason the text is not exactly aligned to the center.
-also it is essential to provide the parent element(within which you wish to center the h1) a width and height.
The correct way to do what you are looking for would be by using absolute and relative positioning.
-give the
.containera position value of relative and theh1a value of absolute-by giving the h1 a width and height we then apply a negative left margin equal to half the width and a negative top margin equal to half the height so that the text is exactly centered.