使用 css 在 html 代码中将文本与网页顶部对齐

aligning text to top of webpage in html code using css

我有这个 css 代码:

.post {
    margin-top: 0.5em;
    margin-left: 2em;
    margin-right: 2em;
    text-align: center;
}

.post p{
    max-width: 1200px;
    padding: .5em;
    text-align: justify;
    margin: 0;
    top: 1.25em;
}

.post h1{
    text-align: center;
}

并在 html 中有这个:

<div class="post">  
 <h1>Title of Sample Work 2</h1>
 <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam dapibus id nisl ut suscipit. Nullam vel justo tellus. Suspendisse vehicula rhoncus nunc sed accumsan. In hac habitasse platea dictumst. Mauris vel dolor velit. Phasellus finibus massa mauris, at interdum nisl luctus at. Etiam porttitor, metus non dapibus pretium, orci arcu pretium nulla, eget congue augue libero at lectus. Mauris pretium urna tristique, laoreet enim rhoncus, euismod tortor.</p>
</div>

这是我看到的:

为什么顶部边距这么大,而文字标题这么低? 您可以在此处查看网络上实际页面的示例: http://www.nanogomo.com/sample1.html

有趣的是,如果我向其中添加更多内容,它会将文本推高。

因为#wrapper 有 display:flex 并且有一个 before。您应该删除以下内容:

#wrapper::before {
    content: '';
    display: block;
}

flex 容器包含 3 个元素 home-back,post 和之前。 Before 是绝对定位的,所以它从正常流中移除(不占用 space)。 Before (with no width) and post are positioned on the main ax (vertical because direction is flex column) with justify-items: space-between (main axis is vertical).

定位在主轴上(垂直,因为方向是弹性列)

使用margin top,根据需要赋值

.post h1{
    text-align: center;
    margin-top: -7px;
}

尝试为边距和填充设置一个值:

.post h1{
    text-align: center;
    margin: 0px;
    padding: 0px;
}