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>