两侧带有水平线

时间:2013-03-21 20:39:24

标签: html css pseudo-class

我正在研究一些CSS,其中设计要求页面标题(标题)以水平线为中心,水平线在两侧垂直居中。此外,页面上有背景图像,因此标题的背景需要是透明的。

我将标题集中在一起,我可以使用伪类来创建该行。但是当我越过标题的文本时,我需要该行消失。

我考虑过使用背景渐变,这些渐变在单词的位置是透明的,但由于每个标题的长度可能不同,我不知道在哪里放置停靠点。

到目前为止这是CSS:

h1 {  
    text-align: center;  
    position: relative;  
    font-size: 30px;  
    z-index: 1;  
}  

h1:after {  
    content: '';  
    background-color: red;  
    height: 1px;  
    display: block;  
    position: absolute;  
    top: 18px;  
    left: 0;  
    width: 100%;  
}  

以下是我所处的位置: http://jsfiddle.net/XWVxk/1/

这可以使用CSS完成,而无需添加任何额外的HTML吗?

3 个答案:

答案 0 :(得分:61)

看看这个http://blog.goetter.fr/post/36084887039/tes-pas-cap-premiere-edition,这是你的答案。

这是您修改的原始代码

h1 {
    position: relative;
    font-size: 30px;
    z-index: 1;
    overflow: hidden;
    text-align: center;
}
h1:before, h1:after {
    position: absolute;
    top: 51%;
    overflow: hidden;
    width: 50%;
    height: 1px;
    content: '\a0';
    background-color: red;
}
h1:before {
    margin-left: -50%;
    text-align: right;
}
.color {
    background-color: #ccc;
}
<h1>This is my Title</h1>
<h1>Another Similar Title</h1>
<div class="color"><h1>Just Title</h1></div>

注意:文章不再在线,这是最后一个好的存档版本: http://web.archive.org/web/20140213165403/http://blog.goetter.fr/post/36084887039/tes-pas-cap-premiere-edition

答案 1 :(得分:33)

几天前需要这个,但接受的答案是不在IE中工作。

这就是我提出的:适用于所有主流浏览器(&gt; = ie8)

jsfiddle:http://jsfiddle.net/gKve7/

HTML:

<h2 class="decorated"><span>My Title</span></h2>

CSS:

/* headlines with lines */
.decorated{
     overflow: hidden;
     text-align: center;
 }
.decorated > span{
    position: relative;
    display: inline-block;
}
.decorated > span:before, .decorated > span:after{
    content: '';
    position: absolute;
    top: 50%;
    border-bottom: 2px solid;
    width: 592px; /* half of limiter */
    margin: 0 20px;
}
.decorated > span:before{
    right: 100%;
}
.decorated > span:after{
    left: 100%;
}

答案 2 :(得分:2)

这可能有效:

.floatClear {
  clear: both;
}
#wrapper {
  text-align: center;
  position: relative;
}
#wrapper .line {
  border-bottom: 2px solid red;
  position: absolute;
  width: 100%;
  top: 15px;
}
#wrapper .textbox {
  position: absolute;
  width: 100%;
}
#wrapper .textbox .text {
  background-color: white;
  margin: 0px auto;
  padding: 0px 10px;
  text-align: center;
  display: inline;
  font-size: 24px;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>HTML</title>
  <link rel="stylesheet" href="main.css" type="text/css" />
</head>

<body>
  <div id="wrapper">
    <div class="line"></div>
    <div class="textbox">
      <div class="text">This is my Title</div>
    </div>
  </div>
</body>

</html>

这里发生的是你在背景线上设置文本,背景颜色加边填充,这样就会隐藏文本块后面的一行。

相关问题