There is a div
element with a width: 50%
and some text inside. Using jQuery, I am calculating the widths of both.
Then, I attempted to horizontally center the text within the div using this jQuery code:
var wrapperWidth = $("#wrapper").width();
var textWidth = $("#text").width();
var horAlign = wrapperWidth / 2 - textWidth;
$("#text").css("margin-left", horAlign);
I basically tried to mimic
margin-left: calc(mydiv - mytext)
in CSS. However, the issue is that the text doesn't appear centered. You can view the problem on this fiddle:
var r = (function () {
var wrapperWidth = $("#wrapper").width();
var textWidth = $("#text").width();
var horAlign = wrapperWidth / 2 - textWidth;
$("#text").css("margin-left", horAlign);
var textHeight = $("#text").height();
var vertAlign = textHeight / 2
$("#text").css("margin-top", - vertAlign);
});
$(document).ready(r);
$(window).resize(r);
#wrapper{
width:50%;
height:400px;
border:solid 5px black;
margin:auto;
margin-top:50px;
}
#text{
font-family: Helvetica, Arial, Sans-Serif;
font-weight:bold;
text-transform:uppercase;
font-size:3.5em;
padding-left:30px;
padding-right:30px;
background:white;
display:inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<p id="text">Test</p>
</div>
What mistake have I made here?