Olie Ayre Olie Ayre - 7 months ago 6
HTML Question

Text moves when parent element is resized

I have a h1 tag in a div that is centred using text-align. The div is centred using margin: auto. I have JQuery that is changing the width of this div but, upon this re-sizing, the text moves to the right a bit. This also happens with the (also centred) menu bar I have below it. This is the code from the JSFiddle:

HTML

<div id="content">
<div id="header">
<h1>Title</h1>
</div>
<div>
<ul class="menu">
<li class="menu"><a class="active" href="#">Text</a></li>
<li class="menu"><a href="#">Text</a></li>
<li class="menu"><a href="#">Text</a></li>
<li class="menu"><a href="#">Text</a></li>
<li class="menu"><a href="#">Text</a></li>
</ul>
</div>
</div>


JQuery

$(document).ready(function() {
var div = $("div");
div.fadeTo(0, 0);
div.fadeTo(1000, 1);
div.animate({width: '+=2%'}, 250);
div.animate({width: '-=2%'}, 500);
});


For brevity, the css is committed from the post but is on the JSFiddle

What is causing this? And how can it be avoided? There is nothing in the CSS that could affect the width or positioning of anything independently.

JSFiddle: https://jsfiddle.net/5vtvzsgc/

Answer

This is because you are changing the width of all divs on the page. To fix this simply change the width of your outer div content:

var div = $("div");

To this:

var div = $("#content");