我正在尝试创建一种带有标题的横幅。但是当我尝试将 <h2>
<div>
中的标题.由于某种原因,它出现在一半。我知道我可以通过输入 margin-top - 20px
来修复它左右,但这让我觉得我必须这样做是不对的。
代码(https://jsfiddle.net/j5ba4ajo/3/):
h2 {
text-align: center;
}
#player-opponent {
width: 545px;
height: 40px;
background-color: red;
float: left;
margin-left:5px;
margin-top:5px;
}
<div id = "player-opponent">
<h2>Player x vs player y<h2>
</div>
最佳答案
<h2>
上有 margin 默认情况下。你必须删除它。将 <h2>
的文本垂直居中你必须设置 height
和 line-height
到 height
你的容器( #player-opponent
):
h2 {
font-family: "Trebuchet MS";
text-align: center;
position:relative;
margin:0;
height:40px;
line-height:40px;
}
#player-opponent {
width: 545px;
height: 40px;
background-color: red;
float: left;
margin-left:5px;
margin-top:5px;
}
<div id="player-opponent">
<h2>Player x vs player y</h2>
</div>
关于html - H2 出现在 div 的中途,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45448218/