强制文本在div之外流动,以不同的颜色居中

时间:2016-12-12 17:03:37

标签: html css

如何获取文字" textetxtetxt"在[ {a: "a"}, {b: "b"} ].inject({}){|sum, e| sum.merge e} 中向左和向右流动innertext以及向左和向右溢出 - 并将outerbox中的文字颜色更改为outerdiv,使其与#000相对背景颜色?

我将#fff的{​​{1}}设置为color,但它不会影响文本颜色。并且outerdiv在任何div上使用#000并不影响margin: 0 auto;中文本的居中或溢出。在小提琴中,innertext的背景色为farouterdiv,目的只是为了使文字可见。

#ddd

我现在在小提琴中有什么:https://jsfiddle.net/amryh49y/5/

What I have now

我希望能够做到这一点,灰色背景上的白色文字是黑色的:

enter image description here

2 个答案:

答案 0 :(得分:4)

使用flexbox和色差与mix-blend-mode对齐。也许是一个简单的演示,但有可能存在。在这种情况下,不需要“outerdiv”。

Mix-blend-mode@MDN

body {
  text-align: center;
}
.farouterdiv {
  padding: 20px 40px;
  border: 1px solid black;
  display: inline-block;
  background-color: #ddd;
}

.outerbox {
  max-width: 100px;
  background-color: #000;
  display: flex;
  justify-content: center;
}
.innertext {
  color: #fff;
  font-size: 36px;
  text-align: center;
  mix-blend-mode: difference;
}
<div class="farouterdiv">

    <div class="outerbox">
      <div class="innertext">texttexttext</div>
    </div>

</div>

答案 1 :(得分:0)

如果您不介意添加其他元素:

&#13;
&#13;
.outerdiv {
  font-size: 50px;
  position: absolute;
}

.innerdiv {
  width: 65px;
  background-color: black;
  color: white;
  height: 1em;
  top: 0;
  left: 50%;
  transform: translate(-50%, 0);
  overflow: hidden;
  position: absolute;
  white-space: nowrap;
}

.text {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translate(-50%, 0);
  white-space: nowrap;
}
&#13;
<div class="outerdiv">
  Hello World
  <div class="innerdiv">
    <div class="text">Hello World</div>
  </div>
</div>
&#13;
&#13;
&#13;

这有一些缺点。 transform可能有点支持if you need older browser support(IE 8及更低版本),您可能会遇到多行条目的问题。但是,根据您的需要,这两种方法都可以解决。

如果您希望偏色div不居中,实际上会变得容易一些

&#13;
&#13;
// Javascript only here to get mouse-over effect.
// Text-coloration can be gotten with just the CSS

var outer = document.getElementsByClassName("outerdiv")[0];
var text = document.getElementsByClassName("text")[0];
var inner = document.getElementsByClassName("innerdiv")[0];

document.addEventListener("mousemove", function(e) {
  var offset = outer.getBoundingClientRect().left;
  var pos = e.clientX - offset
  inner.style.left = pos + "px";
  text.style.marginLeft = -pos + "px";
});
&#13;
.outerdiv {
  font-size: 50px;
  position: absolute;
}

.innerdiv {
  width: 65px;
  background-color: black;
  color: white;
  height: 1em;
  top: 0;
  left: 20px;
  overflow: hidden;
  position: absolute;
  white-space: nowrap;
}

.text {
  position: absolute;
  top: 0;
  margin-left: -20px;
  white-space: nowrap;
}
&#13;
<p><em>mouse over to see effect</em></p>
<div class="outerdiv">
  Hello World
  <div class="innerdiv">
    <div class="text">Hello World</div>
  </div>
</div>
&#13;
&#13;
&#13;

margin-left的{​​{1}}取代.text的{​​{1}}以及距离左边缘黑盒子的距离。