简体   繁体   中英

Cannot center javascript created button using css

I created a button in javascript seen in the code below, but I cannot style it. Neither text-align:center nor margin: 0 auto works. Does any one have a solution? Thanks!

 button = document.createElement("button"); button.innerHTML = "Reset High Score" var body = document.getElementsByTagName("body")[0]; body.appendChild(button); button.addEventListener("click", function() { alert("High Score Reset!"); localStorage.clear(); location.reload(); }) 
 button { margin: 0 auto; text-align: center; } 

The reason is that you don't center inline elements directly, you apply centering to their parent element and the contents of the container get centered. Also, inline elements don't have margins or padding, only block-level elements do.

text-align is an inherited property . That means that it affects its descendant elements rather than itself.

It's incredibly important to know if an element is a block or inline element because, as you've found out the hard way, certain CSS properties only work on one vs. the other.

It's actually pretty easy to spot an inline vs. a block-level element. Block-level elements place their content on a new line, while inline elements do not. So, a div is a block, but a button is an inline. Knowing that, when you look at CSS documentation, you can see if the property works with the type of element you have. In the link I mentioned earlier about text-align , if you scroll down to just above the browser compatibility chart you' see that for text-align , it says that it is an inherited property and applied to blocks.

 button = document.createElement("button"); button.innerHTML = "Reset High Score" var body = document.getElementsByTagName("body")[0]; body.appendChild(button); button.addEventListener("click", function(){ alert("High Score Reset!"); localStorage.clear(); location.reload(); }) 
 body { margin: 0 auto; text-align: center; } 

FYI:

Never, never, never do this: document.getElementsByTagName("body")[0] . Please read this other post of mine that explains how bad this is. Instead, use .querySelector() or, in this case, because you want the one and only body element, which is a child of the document , you can just write document.body .

 button = document.createElement("button"); button.innerHTML = "Reset High Score" var body = document.querySelector("body"); // Instead of getElementsByTagName() var body = document.body; // The easiest way to get a reference to the body element body.appendChild(button); button.addEventListener("click", function(){ alert("High Score Reset!"); localStorage.clear(); location.reload(); }) 
 body { margin: 0 auto; text-align: center; } 

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