8

I want to underline a word with a round brace. This should be part of a C# Text but if it is easier in CSS, no problem. My problem is that the length of the Word can vary, so the bow must by calculated for each word.

My first idea was using CSS box-shadow:

CSS:

#test {
  font-size: 50px;
  background: transparent;
  border-radius: 70px;
  height: 65px;
  width: 90px;
  box-shadow: 0px 6px 0px -2px #00F;
  font-family: sans-serif;
}

HTML:

<div id="test">Hey</div>

output

Unfortunately due to the dynamic Text sizes I can't calculate them.

Is there a smarter approach to this problem?

Trinitrotoluol
  • 205
  • 1
  • 13

2 Answers2

10

You don't need to calculate the width if you use span tags instead.

CSS:

.test {
  font-size: 50px;
  background: transparent;
  border-radius: 70px;
  height: 65px;
  box-shadow: 0px 6px 0px -2px #00F;
  font-family: sans-serif;
}

HTML:

<span id="test" class="test">Hey</span><br/>
<span class="test">Hey this is longer</span>

Working Fiddle: http://jsfiddle.net/Ge8Q3/

entropic
  • 1,683
  • 14
  • 27
  • 3
    Or, if it needs to be `
    `, `

    `, or other block element, add `display: inline=block;` to the CSS for the same effect. Example: http://codepen.io/paulroub/pen/AhoIp

    – Paul Roub Jul 01 '14 at 19:16
  • @PaulRoub Good call, that totally slipped my mind... but you have a little typo: `inline-block` – entropic Jul 01 '14 at 19:20
  • Argh. Yep. The example link has it right, though. Can't seem to go back and edit a comment that's been replied to. – Paul Roub Jul 01 '14 at 19:27
2

I found a different approach.

Working fiddle: http://jsfiddle.net/6pEQA/1/

I used javascript and made the width dynamic:

textWidth function taken from here.

$.fn.textWidth = function(){
    var self = $(this),
        children = self.contents(),
        calculator = $('<span style="white-space:nowrap;" />'),
        width;

    children.wrap(calculator);
    width = children.parent().width(); // parent = the calculator wrapper
    children.unwrap();
    return width;
};

$(document).ready(function(){

    $('#test').css('width',$('#test').textWidth());

});

It also works with h1, div or span. You can check my fiddle. Because it is using span elements to calculate width of the element.

Community
  • 1
  • 1
Bura Chuhadar
  • 3,653
  • 1
  • 14
  • 17