如何将文本定位在边框上方?

4
我已经成功将它应用于白色背景:

enter image description here

但是在背景不是白色的情况下,这种解决方案效果不佳:

enter image description here

我的做法很明显,就是负边距和背景颜色相同。有人知道如何使其始终看起来很好吗?

1
好的,截图比实际的CSS代码更好:P - Šime Vidas
你能把文本的背景设置为透明吗? - Andrew Hagner
3
如何在fieldset的标题文本上面创建背景线样式?请访问 https://dev59.com/T2025IYBdhLWcg3weF6S - Rusty Fausak
1
@rfausak 我想这就是我要找的 :) 谢谢!我还没有测试看看它是否有效。 - Atadj
2
http://www.impressivewebs.com/centered-heading-horizontal-line/ - js-coder
显示剩余2条评论
3个回答

1
一种方法是使用间隔符 span,以及一个包装器(在这种情况下为 header),所有元素都设置了 display 属性,使它们显示为 table-cellexample)。

HTML

<header>
    <span class="spacer"></span><!-- Place this wherever you want the border -->
    <h1>Title</h1>
    <!-- Spacing is automatically added next to elements (but not on ends) -->
    <span class="spacer"></span>
    <a href="http://www.example.com/">View Blog</a>
</header>

CSS

header {
    display:table-row;
    line-height:1.5em;
    font-size:2em;
    white-space:nowrap; /* Prevent titles from wrapping when more than one word is used */
}
header h1 {
    font-size:inherit; /* Change font-size in header */
    overflow:hidden;
    display:table-cell;
    vertical-align:middle;
}
header span.spacer { /* Makes spacers stretch */
    display:table-cell;
    width:50%;
}
header span.spacer { /* Adds spacing on both sides of spacers */
    padding:0 10px;
}
header span.spacer:first-child { /* Adds spacing only on right side of first spacer */
    padding:0 10px 0 0;
}
header span.spacer:last-child { /* Adds spacing only on left side of last spacer */
    padding:0 0 0 10px;
}
header span.spacer:after { /* Adds border to spacer */
    display:inline-block;
    width:100%;
    content:".";
    font-size:0;
    color:transparent;
    height:2px;
    background:#000;
    vertical-align:middle;
    position:relative;
    top:-1px;
}
header > a { /* Styles links according to example */
    font-size:.4em;
    vertical-align:middle;
    background:#25a2a4;
    color:#fff;
    text-transform:uppercase;
    font-family:monospace;
    border-radius:.5em;
    padding:.3em .5em;
    text-decoration:none;
}

谢谢 :) 我会立即测试并告诉您是否有效。 - Atadj
运行得非常顺利。这甚至比评论中提供的链接更好的解决方案 :) 另一个需要图片。非常感谢! - Atadj
@Flow,不客气。请确保在您需要支持的任何浏览器中进行测试。它可以在最新版本的Firefox和Chrome中运行,但我目前无法访问其他浏览器。它应该可以在所有现代浏览器中运行,但不包括IE7。 - 0b10011

0
你是否将文本和按钮放在背景设置为白色的 div 中?如果没有展示 CSS,很难理解您正在做什么。
如果您使用带有背景的 div,请为何不直接删除它?或者如果有一些限制,为什么不将背景设置为 rgba(#,#,#,0.0)?
background:rgba(255,255,255,0.0);

alpha属性有助于设置不透明度的级别。


如果将“background”移除,则边框将显示出来。 - 0b10011
我正在寻找任何容器结构,只需要一个想法。我正在寻找一种创建类似于“----- TEXT -----”的东西的方法,因此我不可能将不透明度设置为0,因为该线将穿过文本。 - Atadj

0
你可以使用 <fieldset> 标签来实现这个功能。
示例:https://jsbin.com/tovuwimezu/edit?html,css,output HTML
<form>
    <fieldset>
        <legend class="blogLegend">New Blog Post</legend>

        blog details here
    </fieldset>
</form>

CSS

.blogLegend {
    font-weight: 600;
    color: rgb(63, 169, 196);
    padding: 10px;
    text-align: center;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接