javascript - 强制在伪元素上不换行(:after)

标签 javascript css

http://codepen.io/ethanclevenger91/pen/vNjOyP

编辑:这个 CodePen 现在展示了各种提议的解决方案

如果您调整这支笔中可用空间的大小,您会看到在顶部标题中,您最终会到达菱形(通过伪元素创建)将换行的点,但最后一个字不会, 所以伪元素在它自己的行上。

我想使用纯 CSS 设计一个解决方案,它的行为类似于第二个标题,如果伪元素中断,最后一个词也会中断。目前我已经通过 Javascript 实现了它,因为标题的内容将来自数据库。

HTML:

<div class="container">
<h1 class="alpha">A heading that takes up nearly the entire width</h1>
<h1 class="alpha solution1">A solution that would require Javascript</h1>
</div>

SCSS:

$brand-primary:lightblue;
$brand-secondary:darken(lightblue, 40%);
@mixin hidpi($ratio) {
  @media (-webkit-min-device-pixel-ratio: $ratio), (min-resolution: #{round($ratio*96)}dpi) {
      @content;
  }
}
body {
  position:relative;
  height:100vh;
  background:$brand-primary;
  width:100%;
}
.container {
  top:50%;
  transform:translateY(-50%);
  position:relative;
}
.alpha {
  text-align:center;
  color:$brand-secondary;
  &:not(.solution1) {
    &:after {
      content:'';
      @extend %diamond;
      margin-left:11px;
    }
  }
  &.solution1 {
    .diamond {
      @extend %diamond;
      margin-left:11px;
    }
  }
}
%diamond {
  width:13px;
  height:14px;
  display:inline-block;
  transform:rotate(-45deg);
  border:1px solid $brand-secondary;
  vertical-align:middle;
  @include hidpi(2) {
    height:13px;
  }
}

JS:

jQuery(document).ready(function($) {
  var content = $('.solution1').html();
  var lastChar = content.slice(-1);
  $('.solution1').html(content.slice(0, -1)+'<span style="white-space:nowrap">'+lastChar+'<span class="diamond"></span></span>');
});

最佳答案

您也可以使用 UTF8 中的标准菱形:

如果你让你的 :after 作为 display: inline 它不会中断,因为你没有在最后一个单词和它之间添加任何空格。

.alpha.solution3:after {
  display: inline;
  content: "◇";
  font-weight: normal;
  font-size: 1.2em;
}
<h1 class="alpha solution3">A solution that does not require Javascript neither a SPAN</h1>

如果这个字符对你来说太粗了,你可以制作自己的字体,使用 font-face 并使用它。

http://codepen.io/anon/pen/BoxjzO

这也适用于不支持 transform 的浏览器。

关于javascript - 强制在伪元素上不换行(:after),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33371213/

相关文章:

javascript - 设置 THREE.PerspectiveCamera 的距离而不改变 View 方向

javascript - 整个主题列表行作为链接

jquery - 同位素过滤按钮状态不起作用

javascript - 更改滚动上的 div 不透明度

css - 修复 dojo MenuItem 的宽度

css - 尽管有过滤器,但 Combres 没有修复相对 URL?

javascript - 仅处理数组中按下的项目

javascript - React - PropTypes 不强制执行 isRequired

javascript - Bootstrap 选项卡中的事件类动态

javascript - 正则表达式(Regex) on CSS3 Transform String