Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify pseudo-element :after's width using javascript [duplicate]

Markup:

<h1 class="title">Hello World</h1>

CSS:

.title {
  border-bottom: 3px solid #aaa;
  position: relative;
}
.title:after {
  content: "";
  width: 100px;
  border-bottom: 3px solid red;
  display: block;
  position: absolute;
}

Demo: http://codepen.io/anon/pen/HDBqe

I wanted to change the .title:after's width based on the text's width, how do I change :after's width using javascript?

$.fn.textWidth = function(){
  var html_org = $(this).html();
  var html_calc = '<span>' + html_org + '</span>';
  $(this).html(html_calc);
  var width = $(this).find('span:first').width();
  $(this).html(html_org);
  return width;
};

$('.title').each(function(){
  // Change :after's width based on the text's width
  // .css('width', $(this).textWidth());
});
like image 660
Jürgen Paul Avatar asked Sep 09 '13 08:09

Jürgen Paul


1 Answers

I've found a trick which works in this case. I've updated your demo:

http://codepen.io/anon/pen/bHLtk

.title {
  border-bottom: 3px solid #aaa;
  position: relative;
  min-width: 100%;
}

.title:after {
  content: "";
  width: inherit;
  border-bottom: 3px solid red;
  display: block;
  position: absolute;
}

Notice, that .title:after has width set to inherit but his parent (.title) has overridden width with min-width. Now I can freely to set width by JavaScript to title and it take effect only on his nested pseudoelement:

$('.title').each(function(){
  $(this).css('width', $(this).textWidth());
});
like image 108
Terite Avatar answered Oct 18 '22 09:10

Terite