如何用CSS自定义下划线的样式

问题描述: 使用:first-letter将首字母的font-size增大后,下划线text-underline也会变粗。 eg: <!doctype html><html><head><style type="text/css">.text{te...

问题描述:

使用:first-letter将首字母的font-size增大后,下划线text-underline也会变粗。


eg:


<!doctype html>
<html>
<head>
<style type="text/css">
.text{
text-decoration:underline;
font-family:Times New Roman;
font-size:24px;
}
.text:first-letter{
font-size:48px;
}
</style>
</head>
<body>
<div class="text">About</div>
<div class="text">Technology</div>
</body>
</html>

效果:attachments-2020-07-3Fnreut95f04382d0c1f3.png


解决方法:


自定义下划线。使用:after,首先添加一个空的内容,为了让它排列到标题的下面,需要将其变成块级元素,用border-bottom设置下划线,可设置其颜色、粗细,下划线的长度通过设置空内容的width属性来实现,还可以通过margin-top调整下划线与文字的距离。


<!doctype html>
<html>
<head>
<style type="text/css">
.text{
font-family:Times New Roman;
font-size:24px;
}
.text:first-letter{
font-size:48px;
}
.text:after {
content:'';
display:block;
width:100px;
margin-top:-5px;
border-bottom:2px solid grey;
}
</style>
</head>
<body>
<div class="text">About</div>
<div class="text">Technology</div>
</body>
</html>

效果:

attachments-2020-07-rG4adYJB5f04380f85415.png


尚存在的问题:


不同文本的长度通常不一致,所需下划线的长度也不一样。



可采取的解决办法:

根据文本的长度设置下划线的长度,可以用jQuery来实现。

<!doctype html>
<html>
<head>
<style type="text/css">
.text{
font-family:Times New Roman;
font-size:24px;
float:left;
clear:left;
width:auto;
}
.text:first-letter{
font-size:48px;
}
.text:after {
content:'';
display:block;
margin-top:-5px;
border-bottom:2px solid grey;
}
</style>
<script src="js/jquery-1.8.2.min.js">
$(document).ready(function(){
$(.text).each(function(){
$(this:after).css("width",$(this).css("width"));
});
});
</script>
</head>
<body>
<div class="text">About</div>
<div class="text">Technology</div>
</body>
</html>

效果:

attachments-2020-07-8RGYYJOV5f0437e0e3e37.png


注意:


1、为使得div的宽度根据内容文字长度而定,需要设置width:auto,而width:auto又需要float:left才有效。


2、clear:left清除float:left带来的左浮动,才能使各个div排在不同行。

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
王凯
王凯

92 篇文章

作家榜 »

  1. admin 651 文章
  2. 粪斗 185 文章
  3. 王凯 92 文章
  4. 廖雪 78 文章
  5. 牟雪峰 12 文章
  6. 李沁雪 9 文章
  7. 全易 2 文章
  8. bngvitmrbj 0 文章