简体   繁体   English

如何在h1标签内将span元素水平居中?

[英]How to horizontally center a span element inside an h1 tag?

I currently have this markup: 我目前有这个标记:

<h1 class="title" id="page-title">
    <span id="page-title-inner">Home</span>
</h1>

And this CSS: 而这个CSS:

h1#page-title { 
    background: transparent url(../images/line.png) 0px 6px no-repeat;
    overflow: hidden;
}

#page-title-inner { 
    width: auto; 
    float: left; 
    background: #fff; 
    padding: 0 15px; 
    position: relative; 
    left: 45%; 
}

This CSS slightly accomplishes what I want given that the page title is short. 鉴于页面标题很短,因此此CSS可以稍微实现我想要的功能。 But if the title is quite long, it fills the space from the center to the right. 但是,如果标题很长,则会从中间到右边填充空白。

What I really want to achieve is to center the page title wrapped inside the span (which is inside the h1 tag) regardless of its width. 我真正想要实现的是将包裹在跨度(位于h1标签内部)内的页面标题居中放置,而不管其宽度如何。

I have tried to do something like: 我试图做类似的事情:

#page-title-inner { 
    width: auto; 
    float: left; 
    background: #fff; 
    margin: 0 auto;
    display: block;
}

where the margin 0 auto value is what would center the span but I wonder why it doesn't work. 边距0自动值是将范围居中的地方,但我想知道为什么它不起作用。

Is there a better way and more efficient to achieve what I want to do? 是否有更好的方法和更有效的方法来实现我想做的事情?

remove float:left & left:45% property of span to make it center. 删除span的float:leftleft:45%属性以使其居中。 Also set text-align:center for your H1 tag. 还要为您的H1标签设置text-align:center

Unless you do something special with the span, you dont need it: 除非您对跨度做一些特殊的事情,否则您将不需要它:

<h1 class="title" id="page-title">
    Home
</h1>
h1#page-title { 
    background: transparent url(../images/line.png) 0px 6px no-repeat;
    overflow: hidden;
    text-align: center;
}

if you do need to do something with the span: 如果您确实需要对跨度做一些事情:

#page-title-inner { 
    /*width: auto;  */
    /*float: left;  */
    background: #fff; 
    padding: 0 15px; 
    /*position: relative; */
  /*  left: 45%; */
}

Float left makes it, well, float left. 向左浮动,使其向左浮动。 And the percentage for the left will never work, because the content of the span can be various sizes 左边的百分比永远都行不通,因为跨度的内容可以是各种大小


You actually dont need to give the span an ID, you can simple do this: 您实际上不需要给跨度一个ID,您可以简单地做到这一点:

h1#page-title span{ /* ... */ }

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

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