简体   繁体   English

将h1以div为背景颜色居中

[英]Centering h1 in a div with background color

I'm having trouble aligning my h1 tag in the center of my div. 我无法在我的div的中心对齐我的h1标签。 The div just displays a block of color and the h1 should fit in the center and right now its sitting at the top. div仅显示一块颜色,并且h1应该位于中间,并且现在它位于顶部。

http://jsfiddle.net/ha632/ http://jsfiddle.net/ha632/

HTML HTML

<div id='title' align="center">
    <h1>ExpressWay</h1>
</div>

CSS CSS

#title{
    background-color: #f5f82e;
    height: 20%;
    text-align: center;
}

Your margins are collapsing . 您的利润正在下降 You can fix this by adding overflow:auto (or a border like border:1px solid #f5f82e ) to your div: 您可以通过在自己的div中添加overflow:auto (或边框,例如border:1px solid #f5f82e )来解决此问题:

#title{
    background-color: #f5f82e;
    height: 20%;
    text-align: center;
    overflow:auto;
}

jsFiddle example jsFiddle示例

Try with this css: 尝试使用此CSS:

#title{
    background-color: #f5f82e;
    height: 20%;
    text-align: center;
    padding: 10px;
}

h1 {
    margin: 0;
    padding: 0;

}

You can play with padding value of #title. 您可以使用#title的填充值播放。

Give your h1 a line-height or add padding to it. 给您的h1行高或为其添加填充。

A better solution would be to just remove the div altogether and apply your styles to the h1 tag instead, unless you have a good reason for the div ? 更好的解决方案是完全删除div然后将样式应用于h1标签,除非您有充分的理由使用div

Example: http://jsfiddle.net/Y6zew/2/ 示例: http//jsfiddle.net/Y6zew/2/

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

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