如何在CSS3中创建OR分隔符?

8

如何用最少的容器仅使用CSS3创建以下内容?

enter image description here

目前,我使用了2个嵌套的div和一个hr标签,这似乎有点过多。


在 CSS 中添加一个“after”怎么样? - chillvivek
你可以使用 :before:after 伪元素。 - Billy
4个回答

10

伪元素!

使用::before::after,你只需要一个容器就可以管理这个。

你需要根据自己的环境调整值,但是总体思路是在容器内绝对定位伪元素。

#or {
  position: relative;
  width: 300px;
  height: 50px;
  
  line-height: 50px;
  text-align: center;
}

#or::before,
#or::after {
  position: absolute;
  width: 130px;
  height: 1px;
  
  top: 24px;
  
  background-color: #aaa;
  
  content: '';
}

#or::before {
  left: 0;
}

#or::after {
  right: 0;
}
<div id="or">OR</div>

使用flexbox而非绝对定位是另一个选项,但是其支持性较差。


1
华丽而实用! - Maximillian Laumeister

8

.or {
  display:flex;
  justify-content:center;
  align-items: center;
  color:grey;
}

.or:after,
.or:before {
    content: "";
    display: block;
    background: grey;
    width: 30%;
    height:1px;
    margin: 0 10px;
}
<div class="or"> OR </div>


1

HTML

<div class="separator"></div>

CSS
.separator {
    width: 100%;
    border-bottom: solid 1px;
    position: relative;
    margin: 30px 0px;
}

.separator::before {
    content: "OR";
    position: absolute;
    left: 47%;
    top: -8px;
    background-color: #fff;
    padding: 0px 10px;
}

代码演示:https://jsfiddle.net/k9jmgdyq/1/


0

HTML

<div class="separator"><label>OR</label></div>

还有 CSS

.separator{
    position: relative;
    text-align: center;
}

.separator label{
    background-color:#fff;
    padding: 0 0.4em;
    position: relative;
}

.separator:before{
    content: '';
    border-style: solid;
    border-width: 0 0 1px 0;
    position: absolute;
    left: 0;
    top: 50%;
    width: 100%;
    border-color:black;
}

Demo http://jsfiddle.net/0e6j7ruc/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接