[英]How to align a HTML element vertically middle?
HTML:
<th class="someCSS">Text</th>
CSS:
.someCSS {
vertical-align: middle;
}
该代码不起作用。 它不会将元素垂直居中对齐。 我怎么做?
在这种情况下,我认为您必须使用flexbox,因为您的文本可以是一个字或500个字,并且始终会停留在页面中间
您将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>
您可以使用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>
完整代码如下:
<!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.