CSS:如何将文本与周围的边框居中 [英] CSS: How to center text with surrounding borders

查看:827
本文介绍了CSS:如何将文本与周围的边框居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一行贯穿整个背景的文本居中对齐.在文本的两边都有一些填充,您根本看不到该行.我为此感到困惑,这是一个仅使用CSS的好方法.这是一个显然错误的jsfiddle,但它是一个开始: http://jsfiddle.net/gtspk/

I am trying to center text that has a line going through the entire background. On either side of the text, there is some padding, where you cannot see the line at all. I am stumped as far as a good css-only way to go about this. Here is a jsfiddle that is obviously wrong, but its a start: http://jsfiddle.net/gtspk/

HTML

<span class="line">
    <h2>Latest Track</h2>
</span>

CSS

.line{display:block; width:100%; border-bottom:1px solid red; margin-top:25px; text-align:center}
.line h2{font-size:15px; text-align:center; position:relative; top:10px; padding:0 15px; display:inline-block; background:white}

这里的问题是我不想指定宽度,因为我将对不同的标题(使用不同数量的文本)重复使用此宽度.通过CSS解决此问题的最佳方法是什么?

The problem here is that I DO NOT want to specify a width, because I will be reusing this for different headers (with different amounts of text). What is the best way to go about this via css?

更新:这是一种方法,但是内联块具有相当糟糕的浏览器支持: http://jsfiddle.net/gtspk/3/

UPDATE: HEre is a way to do it, but inline-block has fairly lousy browser support: http://jsfiddle.net/gtspk/3/

推荐答案

在这里.必须添加一个环绕宽度(必要的是,我们可以将背景设置为白色,以便该行不会碰到文本)

Here you go. Had to add a wrapping span (necessary so we can set the background to white so the line doesn't hit the text)

http://jsfiddle.net/gtspk/9/

<span class="line">
    <h2><span>Latest Track</span></h2>
</span>​

.line{display:block; margin:25px}
.line h2{font-size:15px; text-align:center; border-bottom:1px solid red; position:relative; }
.line h2 span { background-color: white; position: relative; top: 10px; padding: 0 10px;}

对,对不起,您误解了填充的含义.固定的.

Right, sorry, misunderstood what you meant by padding. Fixed.​

这篇关于CSS:如何将文本与周围的边框居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆