简体   繁体   中英

custom underline goes over whole width (css)

I want a custom underline, the color will be different from time to time so i set it with jQuery.

$(".headline h1").css({
"text-decoration":"none",
"border-bottom":"2px solid #00ff0c", 
"padding":"0px"});

It only gives a underline as big as the paragraph, i only want the underline to be under the text itself. How can i do that?

<h1 style="text-decoration: none; border-bottom-width: 2px; border-bottom-style: solid; border-bottom-color: rgb(0, 255, 12); padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; ">Noord-Korea is niet van plan van koers te veranderen</h1>

You can put a span in the h1 that includes the text, then put the bottom border on that instead of on the h1 . Eg:

<h1><span style="text-decoration: none; border-bottom-width: 2px; border-bottom-style: solid; border-bottom-color: rgb(0, 255, 12); padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; ">Noord-Korea is niet van plan van koers te veranderen</span></h1>

Live example

(Side note: I'd recommend moving the style data to a stylesheet rather than using a massive inline style attribute. But that's (ugh) a matter of style.)

Add the following into your stylesheet:

h1 { display: inline-block; }

This will make the width of h1 only as wide as needed for its contents, as opposite to the default 100% width. But note this this also removes the default top and bottom margin of the element, so you may wish to set `margin-top' on the next element.

Give your text an inline element that wraps it like this...

<h1 style="text-decoration: none; border-bottom-width: 2px; border-bottom-style: solid; border-bottom-color: rgb(0, 255, 12); padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; "><span>Noord-Korea is niet van plan van koers te veranderen</span></h1> 

Then apply your style to that inline element.

$(".headline h1 span").css({  "text-decoration":"none",  "border-bottom":"2px solid #00ff0c",   "padding":"0px"});

The reason for this is that h1 is a block-level element so it spans the entire width (like a paragraph); where as, span wraps just the word because it is an inline element.

Removing the border-bottom stuff and using text-decoration underline does solve your problem?

text-decoration: underline;


$(".headline h1").css({"text-decoration":"underline"});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM