Jack Davis
Jack Davis

Reputation: 605

Margins relative to current Div

So I'm trying out the jQuery animation effect through editing the margins to move. The problem is that the when I'm using the animation effect, it's in a div that holds most of my content on the page. The margin I'm editing ends up being relative to the actual page, and not the div it's in. Here is an example:

<html>
<head>

<script src="javascript/jQuery-1.7.1.min.js" type="text/javascript"></script>

<style type="text/css">

#maincontent{
padding-bottom: 3em;
width: auto;
background:#fff;
text-align: left;
margin-left: 10%;
margin-right: 10%;
margin-top: 60px;
}

#animateBox
{
height: 100px;
width: 100px;
background: red;
position: absolute;
}

#moveLeft
{
display: none;
}

#moveRight
{
display: inline;
}

</style>

<script type="text/javascript">
$(document).ready(function() {
    $('#moveRight').click(function() {
        $("#animateBox").animate(
            {"left": "+=200px"},"normal");
            $('#moveRight').css('display', 'none');
            $('#moveLeft').css('display', 'inline');
    });

    $("#moveLeft").click(function() {
        $("#animateBox").animate(
            {"left": "-=200px"},
            "normal");
            $('#moveLeft').css('display', 'none');
            $('#moveRight').css('display', 'inline');

    });
});

</script>

</head>
<body>

<div id="maincontent">

<div id="animateBox"></div>

<br />
<br />
<br />
<br />
<br />

<input type="button" id="moveRight" Value="Move Right" style="width: 100px">
<input type="button" id="moveLeft" Value="Move Left" style="width: 100px">

</div>
</body>

Is there any way to fix this? Thanks.

Upvotes: 0

Views: 185

Answers (1)

Abhidev
Abhidev

Reputation: 7273

Set .maincontent to position:relative in css.

#maincontent{
padding-bottom: 3em;
width: auto;
background:#fff;
text-align: left;
margin-left: 10%;
margin-right: 10%;
margin-top: 60px;
position:relative /*Add this*/
}

Upvotes: 1

Related Questions