H2 set background color and underline

I need help with this CSS issue. I want to stylize an element <h2>so that the background color applies only to the text, as well as to the bottom border.

Here is a preview.

Here is the preview.

I could do it myself, but it’s not so difficult, but the problem is that I can’t add additional elements (like a tag <span>) to the tag <h2>. so I'm looking for a clean css way for this type of styling.

CSS code:

h2 {
    color: rgb(0, 0, 0);
    font: 700 16px Open Sans;
    top: 0px;
    margin: 0px;
    padding: 5px;
    text-transform: uppercase;
    border-bottom: 2px solid rgb(136, 136, 136);
}
+4
source share
3 answers

Live demo

h2{
  font: normal normal normal 20px/1 Helvetica, arial, sans-serif;
  border-bottom: 2px solid #000;
  background:#000;
  color:#fff;

  display:inline-block;
  padding:3px 15px;
  margin-left:10px;
}
h2:after{ /* the line under H2 */
  left:0px;
  display:block;
  position:absolute;
  width:100%;
  height:3px;
  margin-top:2px;
  content: " ";
  background:#000;
}

You can try using :first-linepseudo: DEMO

h2{
  font: normal normal normal 20px/1 Helvetica, arial, sans-serif;
  border-bottom: 2px solid #000;
}
h2:first-line{
  background:#000;
  color:#fff;
}

But you cannot (AFAIK) install the add-on on :first-line


If you can use jQuery LIVE DEMO

JQ:

$('h2').wrapInner("<span />");

CSS

h2{
  font: normal normal normal 20px/1 Helvetica, arial, sans-serif;
  border-bottom:2px solid #000;
}
h2 span{
  display:inline-block;
  margin-left:10px;
  padding:5px 20px;
  background:#000;
  color:#fff;
}
+4

:after:

h2 {
    color: rgb(0, 0, 0);
    font: 700 16px Open Sans;
    margin: 0px;
    background:black;
    color:white;
    padding:10px;
    display:inline-block;
    text-transform: uppercase;
}
h2:after {
    content:" ";
    display:block;
    border-bottom: 2px solid rgb(136, 136, 136);
    background:black;
    width:100%;
    position:absolute;
    left:0;
    margin-top:10px; /*Apply same value of padding-bottom*
}

, :after, h2, h2 .

0

Use :after:

h2 { 
    border-bottom:2px solid black;
    text-transform: uppercase;
    padding-left: 20px;
    position: relative;
    color: white;
}

h2:after {
    content: '';
    position: absolute;
    height: 100%;
    width: 200px;
    background: black;
    left: 16px;
    z-index: -1;
}

Fiddle

-1
source

Source: https://habr.com/ru/post/1523406/


All Articles