How can I make a fieldset legend-style “background

2019-01-06 18:53发布

I'm attempting to style heading text similar to how your default legend text appears in fieldsets; that is to say, I'd like a strikethrough-like line to come up to, but not through, the text. I can't seem to find any information on how I might accomplish this, and since on numerous other questions Google's always directed me to Stack Overflow for answers, I thought someone here may be able to give me advice.

For greater clarity. I'm attempting to get this effect on header text:

                               Centered Header Text                               

Is there any way to do this?

9条回答
贪生不怕死
2楼-- · 2019-01-06 19:58
body { padding-top: 100px; }

div.parent {
    text-align: center;
    border-top: 1px solid #ccc;
}

div.parent div {
    display: inline-block;
    margin-top: -0.8em;
    padding: 0 0.5em;
    background: #fff;
}
<body>
    <div class="parent">
        <div>My Text Here</div>
    </div>
</body>

This is a fluid-width solution that matches your design and should be ok in IE7 (though I'll admit I didn't check). There are a couple of downsides:

  • You lose the fieldset/legend semantics.
  • You can't put a transparent background on the text.

If you don't need it to be fluid-width, onteria_'s solution is probably your best bet.

查看更多
smile是对你的礼貌
3楼-- · 2019-01-06 19:59

I'm not sure if this would suit your need...

h1:before, h1:after {
 content: " ------------- ";
}
查看更多
霸刀☆藐视天下
4楼-- · 2019-01-06 20:00

I came up with a quick, image-less solution that seems to work pretty well in IE 8+ and other browsers, whilst gracefully degrading in IE 6/7:

<h1>CSS 2.1 EXAMPLE</h1>
h1 { position: relative; text-align: center; }
h1:first-line { background-color: white; }
h1:before {
    position: absolute;
    z-index: -1;
    content: '';
    left: 0px;
    right: 0px;
    height: 1px;
    top: 50%;
    background-color: black;
}

It does come with the following limitations, though:

  • The text must match the overall background colour exactly, otherwise it will look weird.
  • If you want any kind of padding on the text, you need to use non-breaking spaces at either side of the text (see demo).
  • Heading text must always be on one line (works best if fixed width).

Here's a demo: http://jsfiddle.net/AndyE/3tFQJ/

查看更多
登录 后发表回答