简体   繁体   English

如何将HTML元素垂直居中对齐?

[英]How to align a HTML element vertically middle?

HTML: HTML:

<th class="someCSS">Text</th>

CSS: CSS:

.someCSS {
    vertical-align: middle;
}

This code is not working. 该代码不起作用。 It doesn't align the element vertically middle. 它不会将元素垂直居中对齐。 How do I do that? 我怎么做?

In this case you have to work with flexbox I think because your text can be one word or 500 and it will always stay in the middle of the page 在这种情况下,我认为您必须使用flexbox,因为您的文本可以是一个字或500个字,并且始终会停留在页面中间

you put a div around your text and then you do what I post 您将div放在文本周围,然后执行我发布的操作

 body{ margin:0px; } .test{ display:flex; /*justify-content:center;*//*to put in the center of the screen*/ align-items:center; width:100%; height:100vh; } 
 <div class="test"> <th class="someCSS">Text</th> </div> 

You can use the css calc() function to work out the centre point of the containing element and then subtract half the height of the element you wish to center. 您可以使用css calc()函数算出包含元素的中心点,然后减去要居中元素的高度的一半。

.container {
  height: 100vh;
}
.element-to-align{
  position: relative;
  top: calc(50% - 50px);
  height:100px;
  width: 100px;
}



<body>
 <div class="container">
  <div class="element-to-align"></div>
 </div> 
</body>  

Full code below: 完整代码如下:

 <!DOCTYPE html>  
 <html lang="en">  
 <head>  
 <meta charset="UTF-8">
 <title>Document</title>
 <style>
 .container {
   height: 100vh;
 }
 .element-to-align{
   position: relative;
   top: calc(50% - 50px);
   height:100px;
   width: 100px;
   border: red dotted 1px;
 }
</style>
</head>
<body>
 <div class="container">
   <div class="element-to-align"></div>
 </div> 
</body>
</html>
<style>
        #txt{
            vertical-align: middle;
            height: 190px;
        }
</style>


    <table border="1">
        <tr>
            <th id="txt">Some Text</th>
        </tr>
    </table>

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

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