Skip to content

Commit 0cff60f

Browse files
committed
Correctly calculate element size. cburgmer#78
1 parent b97347c commit 0cff60f

File tree

2 files changed

+25
-4
lines changed

2 files changed

+25
-4
lines changed

src/browser.js

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -163,9 +163,18 @@ var browser = (function (util, proxies, ayepromise, sanedomparsererror, theWindo
163163
return documentClone.querySelector(tagName);
164164
};
165165

166+
var elementToFullHtmlDocument = function (element) {
167+
var tagName = element.tagName.toLowerCase();
168+
if (tagName === 'html' || tagName === 'body') {
169+
return element.outerHTML;
170+
}
171+
172+
// Simple hack: hide the body from sizing, otherwise browser would apply a 8px margin
173+
return '<body style="margin: 0;">' + element.outerHTML + '</body>';
174+
};
175+
166176
module.calculateDocumentContentSize = function (element, options) {
167-
var html = element.outerHTML,
168-
defer = ayepromise.defer(),
177+
var defer = ayepromise.defer(),
169178
zoom = options.zoom || 1,
170179
iframe;
171180

@@ -192,7 +201,7 @@ var browser = (function (util, proxies, ayepromise, sanedomparsererror, theWindo
192201
// srcdoc doesn't work in PhantomJS yet
193202
iframe.contentDocument.open();
194203
iframe.contentDocument.write('<!DOCTYPE html>');
195-
iframe.contentDocument.write(html);
204+
iframe.contentDocument.write(elementToFullHtmlDocument(element));
196205
iframe.contentDocument.close();
197206

198207
return defer.promise;

test/specs/BrowserSpec.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -351,12 +351,24 @@ describe("Browser functions", function () {
351351
});
352352
});
353353

354-
it("should calculate the correct size given any DOM element", function () {
354+
it("should calculate the correct size given any DOM element", function (done) {
355355
setHtml('<div><style>div { width: 400px; height: 400px; }</style></div>');
356356

357357
browser.calculateDocumentContentSize(doc.querySelector('div'), {width: 300, height: 200}).then(function (size) {
358358
expect(size.width).toBe(400);
359359
expect(size.height).toBe(400);
360+
361+
done();
362+
});
363+
});
364+
365+
it("should not have the body margin influence a DOM element sizing", function (done) {
366+
setHtml('<div><style>span { display: inline-block; float: left; width: 200px; height: 200px; }</style><span></span><span></span></div>');
367+
browser.calculateDocumentContentSize(doc.querySelector('div'), {width: 400, height: 200}).then(function (size) {
368+
expect(size.width).toBe(400);
369+
expect(size.height).toBe(200);
370+
371+
done();
360372
});
361373
});
362374

0 commit comments

Comments
 (0)