标题的底部边框小于宽度

我需要用小于h2标题宽度的下边框创build下划线效果 。 通常我不上传图片,但我认为这可能有助于进一步解释这个问题:

标题的下边框小于宽度

你可以使用一个伪元素。 (例)

 .pseudo_border { position:relative; display:inline-block; } .pseudo_border:after { content:''; position:absolute; left:0; right:0; top:100%; margin:10px auto; width:50%; height:6px; background:#00f; } 

只是相对于父元素绝对定位一个伪元素。 将其从top定位为100% ,并使用left:0; right:0的组合left:0; right:0 left:0; right:0和水平居中的auto margin 。 相应地修改元素的高度/宽度,并更改间距的margin-top

其他方法:

阴影传播半径的方块阴影:

 body{text-align:center;} h2{ font-size:40px; color:#409FB3; display:inline-block; height:50px; box-shadow: 0 25px 0 -23px #5CC7A8; } 
 <h2>Some title</h2> 

你也可以使用linear-gradient来做到这一点。 在这种方法中,使用渐变创build一个小的背景图像,使其对于第一个和最后一个25%是透明的,而其余的50%是具有颜色的(因此看起来像是实际的h2文本的50%)。 然后将此背景放置在元素的底部,使其看起来像下边框。 边框的大小可以通过修改背景大小来改变。

即使h2内的文字量有变化,效果也会保持良好。 然而,主要的缺点是与伪元素或盒子阴影方法相比,对梯度的浏览器支持相对较差。

注意:在答案中使用脚本只是为了避免浏览器前缀:)

 h2{ display: inline-block; text-align: center; padding: 10px 10px 15px; /* bottom padding should be higher to make up for pseudo border height */ background: linear-gradient(90deg, transparent 25%, lightseagreen 25%, lightseagreen 75%, transparent 75%); background-size: 100% 5px; background-position: 0% 100%; background-repeat: no-repeat; } .semitransparent{ background: linear-gradient(90deg, transparent 25%, lightseagreen 25%, lightseagreen 75%, transparent 75%), linear-gradient(90deg, transparent 0%, rgba(50,50,50,0.25) 0%); background-size: 100% 5px, 100% 100%; background-position: 0% 100%, 0% -5px; background-repeat: no-repeat; } .colored{ background: linear-gradient(90deg, transparent 25%, lightseagreen 25%, lightseagreen 75%, transparent 75%), linear-gradient(90deg, transparent 0%, aliceblue 0%); background-size: 100% 5px, 100% 100%; background-position: 0% 100%, 0% -5px; background-repeat: no-repeat; } /* Just for demo */ body{ background-image: radial-gradient(circle, #3F9CBA 0%, #153346 100%); font-family: Calibri, Tahoma; text-align: center; } 
 <script src="ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script> <h2>Some Text</h2><br/> <h2 class='semitransparent'>Some Lengthy Text</h2><br/> <h2 class='colored'>Some more examples yay!!</h2> 

你可以使用一种“假的”边界,只需在它周围包裹一个div,并在标题之后制作一个边框

的jsfiddle

HTML

 <div id="border-wrapper"> <h2>My address</h2> <div id="border"></div> </div> 

CSS

 #border-wrapper{ position:relative; display:inline-block; } #border{ position: relative; width: 50%; height: 2px; background-color: blue; margin: 0 auto; } 
 h2 ::after { background: #f1991b none repeat scroll 0 0; content: ""; display: block; height: 2px; margin-top: 15px; width: 50px; 

}

 <style> .main{ text-align:center; } .title{ font-weight: 300; display: inline-block; padding-bottom: 15px; position: relative; } .title::after { content: ""; position: absolute; width: 50%; height: 1px; bottom: 0; left: 0; border-bottom: 3px solid #ff5533; right: 0; margin: 0 auto; } </style> <div class="main"> <h1 class="title"> Your Title </h1> </div>