html - 在 div 元素中水平和垂直居中对齐文本

标签 html css

<分区>

I have made a div of fixed height and I want the text to align both vertically and horizontally in the div.

I tried using margin:auto and text-align but it didn't help.

I am beginner HTML/CSS.

 <!DOCTYPE html>
    <html>
    <body>
    
    <div style="background-color:black;color:white;padding:20px; height:400px;">
      <h2>London</h2>
      
    </div>
    
    </body>
    </html>

最佳答案

h2 {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

关于html - 在 div 元素中水平和垂直居中对齐文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39177599/

相关文章:

javascript - 将鼠标悬停在 CSS 中的列表项上时如何触发 div 可见性?

javascript - 是否可以覆盖 box-sizing :border-box?

css - 继承多个nth-child时重置nth-child "clear: both"

javascript - 不要预览菜单顶部导航中的第一项

css - 从底部开始呈现水平列表项

php - slider 中图像之间的空白空间

javascript - 根据底层颜色更改固定文本的颜色

html - 表格中的 Angular 搜索

html - 如何仅将水平单元格间距应用于 HTML 表格?

jquery - bootstrap carousel ID 和类问题