How can I make a fieldset legend-style “background line” on heading text?

前端 未结 9 1336
后悔当初
后悔当初 2020-11-29 08:31

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 no

9条回答
  •  再見小時候
    2020-11-29 09:22

    With flexbox being supported by all the latest browsers out there, and it being five years since the IE8 requirement was mentioned by the author, I wanted to have some fun building a new solution using that.

    A variety of examples getting more complicated:

    https://jsfiddle.net/0mL79b4h/1/

    https://jsfiddle.net/0mL79b4h/2/

    CSS

    div {
      display: flex;
      align-items: center;
    }
    
    div:before,
    div:after {
      border: 1px solid #000000;
      border-radius: 2px;
      height: 2px;
    
      display: block;
    
      content: "";
      flex: 1;
    
      width: 100%;
    }
    
    h1 {
      text-align: center;
    
      margin: 8px;
    }
    

    HTML

    Example Text

    Multi-Line
    Example Text

    Pros:

    • Uses flexbox!
    • Super simple HTML.
    • Left and right sides can be adjusted for asymmetry.
    • Zero background issues, no inheriting colors, etc.
    • Fluid width.
    • Multi-Line support.
    • Left/Center/Right/Custom Alignment: Just adjust the flex property separately for the before and after elements, higher numbers will dedicate more space to that side. Remove one entirely to left or right align it.
    • Interesting effects by playing with the border style (I actually chose a round border in this example). Set height to 0px and use border-top instead for a generic line.

    Cons:

    • Uses flexbox. Call me lazy, but I didn't build in any backward compatibility in this example so it'll look odd on a browser that supports psuedo elements but doesn't support flexbox, although last I checked that was Chrome (Firefox, etc), which are all automatically updated anyway. Might want to use some Modernizr.

提交回复
热议问题