CSS
right aligned next to text

2020-02-01 03:04发布

问题:

I need a h2 that has a heavy stroke to the right of it. Like so:

I'm struggling with the best, responsive way to accomplish it. Not to mention that it's in a custom WP theme, so I don't want to create a ton of on page markup that the client will break immediately :)

回答1:

What you need is a single element and an :after pseudo. P.S It's responsive.

Demo

Explanation: Here, the main part is to use overflow: hidden; on the element, and than am creating a virtual element using an :after pseudo with content property, and am positioning it absolute to the parent element which am setting to relative

<h2>Hello World</h2>

h2 {
  font-size: 20px;
  font-family: Arial;
  position: relative;
  overflow: hidden;
}


h2:after {
  display: inline-block;
  content: "";
  height: 4px;
  background: #f00;
  position: absolute;
  width: 100%;
  top: 50%;
  margin-top: -2px;
  margin-left: 10px;
}


回答2:

Here you go with a fully responsive solution.

WORKING DEMO

The HTML:

<h2 class="title">Who we are</h2>
<div class="red">&nbsp;</div>

The CSS:

.red{
background:#ff0000;
position:relative;
margin-top:-17px;
height:5px;
z-index:-1;
}

.title{
background:#ffffff;
display:inline;
padding-right:20px;
}

Hope this helps.

PS: You can change the margin/padding accordingly to match your needs as well as media query requirements.