user5314244
user5314244

Reputation:

Jquery adding and positioning div at center of parent div

i am trying to add div dynamically and also try to position it center of its parent div but nothing happen when clicking add button.

here is my small code

if ($('#dvChild').length==0)
{

        var parent = $('.parent');
    //var parentDimensions = parent.height() * parent.width();

    var child = $('.child');
    //var childDimensions = child.height() * child.width();

    var $divChild = $("<div>", {id: "dvChild"});
        $divChild.css({top: parent.height()/2 - child.height()/2 , left: parent.width()/2 -         child.width()/2 }) 
        $("#dvParent").append($divChild);
}

full code found in jsfiddle https://jsfiddle.net/tridip/kzym5mu9/1/

please tell me where i made the mistake. thanks

Upvotes: 0

Views: 383

Answers (3)

Henrik Clausen
Henrik Clausen

Reputation: 729

This is possible with CSS alone, like this:

<div style="width:400px; height:400px; display:table-cell; background-color:#f00; vertical-align: middle; text-align: center;">
<div style="display:inline-block;">asdasdsafsasfd</div>
</div>

On the parent; add "display;table-cell;vertical-align: middle;text-align: center;"

On the child; add "display:inline-block;"

Upvotes: 0

Adharsh M
Adharsh M

Reputation: 2812

Change CSS and jQuery as follow

$("#btnadd").click(function () {
    if ($('#dvChild').length==0)
    {
    	var divChild = "<div id='dvChild'></div>";
		$("#dvParent").append(divChild);
    }
});
$("#btnDel").click(function () {
   $("#dvChild").remove();

});
.parent { 
  width: 200px;
  height: 200px; 
  background-color:red;
  position: relative;
}

#dvChild {
    height: 100px;
    width: 100px;
    background-color:yellow;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div id="dvParent" class="parent">parent div</div>
<br>
<button id="btnadd">Add Div</button>
<button id="btnDel">Remove Div</button>

Upvotes: 0

Keith
Keith

Reputation: 4147

Here is an simpler way to get what you need done:

https://jsfiddle.net/kzym5mu9/4/

$("#btnadd").click(function () {
    $('#dvParent').append('<div class="child">child</div>');
});

$('#btnDel').click(function(){
    $('.child').remove();
})

.child {
    height: 50%;
    width: 50%;
    background-color:yellow;
    position: absolute;
    top: 25%;
    left: 25%;
}

Upvotes: 1

Related Questions