CSS Текст исчезает - Подробнее с фоновым изображением, которое не solid цвет - PullRequest
0 голосов
/ 18 марта 2020

У меня есть страница с фоновым изображением, похожим на пергаментную бумагу. Есть длинный текстовый раздел, в котором мы хотим добавить последнюю строку или около того в первом абзаце, а затем добавить кнопку «Читать далее», чтобы раскрыть остальные. Есть много примеров использования зацветающего текста с фоном solid, но я не могу найти ни одного, использующего фоновое изображение (это не цвет solid). (страница: https://kringle.cash/goodwillFade.php)

Я пробовал около 20 различных примеров и до сих пор не смог ни один из них преобразовать в фактическое использование всего эффекта затухания текста с реальное изображение в качестве фона.

По общему признанию я не очень опытен с CSS и эффектами, поскольку я - программист внутреннего интерфейса по профессии. Любая помощь будет принята с благодарностью.

TIA

Ответы [ 2 ]

0 голосов
/ 18 марта 2020

Нет простого способа решить вашу проблему. Ваше фоновое изображение - JPG с solid цветами. Простого изменения opacity недостаточно. A linear-gradient сам по себе мало что может сделать с solid изображением.

Итак, что я сделал:

  • Создал новое изображение «note_back» с Photoshop, белый фон , добавил шум (с fg-color white и bg-color # d5d5d5), удалил много белых пикселей, чтобы получить прозрачность, сделал очень слабое размытие по Гауссу (0.4) и сохранил файл в формате PNG (с альфа-каналом).
  • Новый PNG теперь используется как background-image как для <body>, так и для верхнего и нижнего градиентов .container вместо исходного JPG. Это [ОБЯЗАТЕЛЬНО], чтобы решение работало.
  • body {background-color: rgba(220,220,220,1)} используется для заливки какого-либо цвета для удаленных пикселей PNG (подойдет любой цвет, но нам нужно держаться ближе к оригиналу).
  • background-color: rgba(220,220,220,.8), слегка прозрачный, чтобы пиксели просвечивали для верхней и нижней градиента.
  • Вместо использования background-image для linear-gradient мы используем mask-image с градиентом от черного к прозрачному, который постепенно блокирует пиксели. (Я не знаю технику, лежащую в основе этого, но она имеет отношение к входным и выходным пикселям XOR).

Я создал демонстрацию с большим и жирным текстом, чтобы увидеть эффект (который в противном случае был бы трудно с этими светлыми цветами). Увеличьте, если нужно, это действительно работает ....

Код:

/*******************/
/* SO60741467 demo */
/*******************/
body { /* [MANDATORY] (parent container) */
    background-color: rgba(220,220,220,1); /* darkest color that appears in 'background-image' */
}

.container { position: relative } /* [MANDATORY] stacking context for :before/:after */

body,
.container:before,
.container:after { /* [MANDATORY] */
    background-image     : url(https://i.stack.imgur.com/HvnVb.png); /* background image PNG with transparent pixels */
    background-repeat    : repeat;
    background-attachment: fixed;
}

.container:before,
.container:after { /* [MANDATORY] */
    position: fixed; left: 0; width: 100%; height: 6rem; content: '';
 
    /* same as <body> but with subtle transparency, adjust to needs */
    background-color: rgba(220,220,220,.8);
}
.container:before { /* [MANDATORY] */
    top: 0;     /* position at top of text */
                /* start with solid color, end transparent */
    mask-image: linear-gradient(rgba(0,0,0,1) 0%, rgba(0,0,0,0) 75%);
}
.container:after { /* [MANDATORY] */
    bottom: 0;  /* position at bottom of text */
                /* start transparent, end with solid color */
    mask-image: linear-gradient(rgba(0,0,0,0) 0%, rgba(0,0,0,1) 75%);
}
/************************/
/* personal preferences */
/************************/
html,body             { box-sizing: border-box; width: 100%; max-width: 100%; height: 100%; margin: 0 }
*::before,*::after, * { box-sizing: inherit }

/******************/
/* eye-candy only */
/******************/
/* responsive document font-size */
html { font-size: calc(0.625vmin + 12px) } /* y=mx+b for p1(320,14) p2(1280,20) */
body { font-size: 1rem }

.container {
    width: calc(61.25vmin + 104px); /* y=mx+b for p1(320,300) p2(1920,1280) */
    margin: 0 auto;                 /* center horizontally */
    font-size: 1.5em;               /* larger font to fill screen with text */
    font-weight: bold;              /* to see effect even better */
}
<div class="container">
    <h2>Lorem Ipsum</h2>
    <p>Lorem ipsum dolor sit amet, exerci dolorem est ad. Sumo rebum prompta vim ad. Legendos expetendis id sed. Ex ius quem accusamus, pri et
        deleniti copiosae.</p>
    <p>Cu vel debet nobis, repudiare deseruisse reprehendunt usu ad. Ex elit idque nam. Omnis munere detraxit mei te, eu labore appareat verterem
        est. Mel ex oporteat consectetuer.</p>
    <p>Pro ea nonumy integre, mel at solum corpora. Id viris audiam repudiare cum, pri dolore appareat ex, per propriae detracto tacimates ex.
        Elitr sapientem quo et, usu suas porro tibique cu. Iusto causae eos et, tota principes interesset et eos. Similique intellegam cum ei, unum
        qualisque mel et, regione verterem delicatissimi qui ut. Aliquam incorrupte ea pro, vel veritus consequat id.</p>
    <p>Pri te amet electram. Tation commodo minimum cu pri, utamur minimum id pri. No legimus atomorum vim. Vix id putent iuvaret salutandi, mel
        phaedrum conceptam ut.</p>
    <p>Nam id utinam referrentur, similique intellegebat ad mel, eu nobis aeterno qui. Ad quodsi cetero sed, deserunt disputando nam an, veri
        viderer consetetur vel an. Zril vivendo pro no, oratio scripta quo eu, aeque elaboraret duo et. Ea nonumy essent sed, enim cetero pri an. An
        zril facete ius.</p>
    <p>Id delectus fabellas praesent duo, ei vim consequat democritum. An mei tamquam iuvaret philosophia, amet vitae usu at. Errem equidem eam
        eu, per sumo audire vocibus an, ridens laoreet duo ut. Pro te velit efficiendi, an ius tation noster. Inimicus argumentum eu quo, no invenire
        mandamus philosophia nam. Simul placerat efficiendi eu eum.</p>
    <p>Sed ex quas mazim intellegam. Ad harum dicant sanctus vis, etiam assum complectitur his ex, solum noster instructior id mei. His brute
        facilis adversarium eu, vix officiis persecuti incorrupte te. Te odio mundi sanctus has. Cetero blandit pertinax te cum, cum solet
        theophrastus ex.</p>
    <p>Erant iudico ei nam, no nihil malorum vituperatoribus mel. Graeci pericula eos cu, ad oratio partem abhorreant quo. No aeterno fastidii
        legendos vel, pro vide dissentiet an. Possit epicurei definiebas eos no, eum no diam augue. Sed ex tritani diceret tacimates, ea latine
        singulis interpretaris vis, vel quaestio definiebas at.</p>
    <p>Ei scripta imperdiet has. Wisi vivendo pri te, mel lorem quodsi sensibus ne, in cum eripuit platonem evertitur. Vis an quis possit
        voluptatibus. Eum fastidii appareat id. Augue elitr bonorum per at, nam ne veri possit scribentur.</p>
    <p>An probo etiam sit, ut agam epicuri similique eum. Dicam iuvaret in mel, no has consul causae vocibus, ad veniam aperiam voluptatibus sed.
        Posse inimicus necessitatibus pri an, no sed invidunt laboramus. Nostrum sadipscing ex sea, ad pro idque suscipiantur.</p>
</div>
0 голосов
/ 18 марта 2020

Простой взлом - используйте основной фон для эффекта затухания.

HTML

<div class="container">
  <p class="container__content">
    Note: This is just a hack.
    Your implementation may differ.
    This example only has the visual part display part i.e
    showing fading option before the full document is shown.
    You need to hide the pesudo class on button click.
  </p>
  <button class="container__more-btn">Read More</button>
</div>

CSS

.container {
  position: relative;
  background: url(img.jpg);
}

.container__content {
  position: relative;
}

.container__content::after {
  position: absolute;
  content: '';
  width: 100%;
  height: 2rem;
  background: url(img.jpg);
  left: 0;
  bottom: 0;
  opacity: 0.7;
}

.container__more-btn {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translate(-50%, 50%);
}

отрегулируйте высоту и непрозрачность в контейнере ___ контенте :: после согласно необходимости.

Также измените изображение , Не стесняйтесь спрашивать, если что-то неясно.

...