简体   繁体   中英

Add margin to the <html> element with JavaScript

I'm looking to add some top margin to the entire but I think I'm not referring to the element properly.

This is what I have:

getElementsByTagName("html").style.marginTop = top_height;

I'm guessing there must be another way to refer to the <html> tag since it's kind of a unique tag, but I haven't found how to after a lot of searching. I'm probably not running the right searches. Hope someone can help me out here.

You should apply the margin to the body instead as it is the root of the visible elements.

Also, getElementsByTagName is off of document and returns an list of elements. document.querySelector('body') will return the first one or you could just use document.body as Jaromanda recommended.

I'm guessing there must be another way to refer to the <html> tag since it's kind of a unique tag

There is. In fact, there is a property of document for it. It is document.documentElement .

This property brings with it improved performance, as it does not need to run any document queries, and can be used to access the root element with other document types, such as SVG.

我建议向正文添加边距,而不是!DOCTYPE html属性。

getElementsByTagName("body").style.marginTop = top_height;

You need to add document. before the getElementsByTagName and then since this particular function returns an array of matched tags you can do the following (try it in your browser Console and watch stackoverflow shift down 6 pixels):

document.getElementsByTagName("html")[0].style.marginTop = "6px";

Like @Alexander O'Mara mentioned the document.documentElement is a much better way to access the html element so then your code would be like this:

document.documentElement.style.marginTop = "6px";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM