首页 > 解决方案 > 基于居中背景图像反转字体颜色 - CSS

问题描述

我正在尝试重新创建它,使用始终居中文本的 CSS 并动态反转背景图像前面的字符。

设计

我当前的 codepen 示例使用伪元素和属性内容,但是我无法将文本居中以匹配上面的图像,它仅适用于左对齐的内容。

https://codepen.io/graham-cooper/pen/vYGyLeV

<div class="inverted-text-element" data-content="BOOK A VIEWING">

.inverted-text-element {
    position:relative;
    max-width:600px;
    margin:0 auto;
}

.inverted-text-element:after {
    background:url('https://farm9.staticflickr.com/8760/17195790401_94fcf60556_c.jpg');
    background-size:cover;
    color:#FFFDED;
    width:240px;
    left:120px;
}

.inverted-text-element:before, .inverted-text-element:after {
    padding: 100px 0;
    text-indent: 10px;
    position: absolute;
    white-space: nowrap;
    ccolor: #99794C;
    overflow: hidden;
    font-size:160px;
    content: attr(data-content);
}

标签: htmlcss

解决方案


https://jsfiddle.net/ja63f2zb/

HTML:

<div class="box">
    Lorem ipsum.
    <span>Lorem ipsum.</span>
</div>

CSS:

.box {
    width: 200px;
    margin: 200px auto;
    height: 400px;
    background-color: #CCC;
    font-size: 8em;
    position: relative;
}
.box span {
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    overflow: hidden;
    color: #FFF;
}
.box, .box span {
    display: -webkit-flex;
    display: -moz-flex;
    display: -ms-flex;
    display: -o-flex;
    display: flex;
    -ms-align-items: center;
    align-items: center;
    justify-content: center;
    white-space: nowrap;
}

只是不要忘记可访问性

<div class="box">
    Lorem ipsum.
    <span aria-hidden="true">Lorem ipsum.</span>
</div>

推荐阅读