Search code examples
jquerycssjquery-clone

jQuery clone() on a div positions it weirdly


I have an empty div in body, with the following CSS:

div{
    border: 1px solid black;
    width: 100px;
    height: 100px;
    display: inline-block;
}

http://jsfiddle.net/CcmFJ/1/

I then use jQuery to clone the element a few times. In the result, why is the original one taking up extra margin?


Solution

  • It's actually due to the white space being injected by the .append() method. You end up with this:

    <body style="">
      <div></div>
    
    
    
    
    
    
    <div></div>...
    

    If you use .after() and insert the divs like this:

    for (var i = 0; i < 20; i++){
        $("div:first").after($("div:first").clone());
    }
    

    you get no extra white space before the clones. jsFiddle example