简体   繁体   English

需要帮助使用 javascript 将 html 元素居中

[英]Need help centering html elements using javascript

I need the JavaScript to align the footer and h1 to the center of the page, the function adjust should align the footer and h1 to the center of the page.我需要 JavaScript 将页脚和 h1 对齐到页面的中心,function 调整应该将页脚和 h1 对齐到页面的中心。

 function adjust(){ document.querySelector("header h1").style.display = "center"; document.querySelector("footer").style.display = "center"; }
 <,DOCTYPE html> <html> <body> <main> <div> <h1>h1 text</h1> <p>Lorem ipsum dolor sit amet.consectetur adipisicing elit, Perspiciatis magni reprehenderit quibusdam ipsam eius odit iste consequatur necessitatibus voluptatibus deserunt maxime esse, similique. cupiditate facere quisquos iddelectus est,</p> </div> <div> <h2>Two</h2> <p>Lorem ipsum dolor sit amet. consectetur adipisicing elit, Autem magni voluptatibus tempore aut corrupti. ducimus optio consequuntur, Quasi debitis a dicta natus voluptas alias ea, quis excepturi ut. eius accusantium.</p> </div> </main> <footer> <p>FOOTER</p> </footer> <script src="main.js"></script> </body> </html>

The CSS property you are looking for is text-align , not display .您正在寻找的 CSS 属性是text-align ,而不是display It's text-align: center;它是text-align: center; . .

Remember that hyphen-separated properties get camel-case property in JavaScript, so it becomes:请记住,连字符分隔的属性在 JavaScript 中获得驼峰式属性,因此它变为:

document.querySelector("header h1").style.textAlign = "center";

simple use text-align: center.. if your problem still exist then use flexbox "display:flex; justify-content: center; align "简单使用 text-align: center .. 如果您的问题仍然存在,请使用 flexbox "display:flex; justify-content: center; align "

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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