CSS background for text only & not parent span/div/body? - html

I'm not sure this is possible, but i was wondering if it is possible to set a background color for text only, & not the span/div/P tags that contain the text.
EG
This text here...
each character of "this" will be a black background with white text, the 'space' will have the blue background the word "text" will be a black background with white text etc....
Something like what deaf people see on some TV shows - captions...
But I don't want to contain each / every word with a div or span - as that will make the total HTML coding huge...
From what i have gathered / googled, I can set a background for an entire 'container' but not just for "text" in the container.
example: How do I set background color of text only in CSS?
The above sets the whole h1 tag as a green background.
PS - i'm only using 'green' as an example - but i've got other colours in mind, or even pictures as the background. but i want the text content to be visible..
PS, if the above can be done, is it also possible to 'opaque' the text-background ? so the actual / main background is partially visible, but keep the text "solid".
Ive used opaque, but it makes the foreground text opaque (not kept as solid).

This is the solution I found using JavaScript. It is definitely not only CSS, but it's as far as I could get it with minimal code:
Note: check the updated JSFiddles below! http://jsfiddle.net/fq4ez69t/1/
It finds all spaces in your "p" tags (i.e. change this to whatever you need) and substitutes them with a span with class .space so that you can style it in your CSS.
Here's the JS:
var str = document.getElementsByTagName("p")[0].innerHTML;
var newstring = str.replace(/ /g, '<span class="space"> </span>');
document.getElementsByTagName("p")[0].innerHTML = newstring;
Update #1
Just thought of this. Maybe change the getElementsByTagName("p")[0].innerHTML; to something like document.getElementsByClassName('shaded')[i]; and use this class on whatever text you want to look like that. This is done using a for loop like so:
http://jsfiddle.net/fq4ez69t/2/
Just add the class shaded to the text element you want to look like the image above and voila!
var shadedtextblocks = document.getElementsByClassName("shaded");
for(var i = 0; i < shadedtextblocks.length; i++)
{
var str = shadedtextblocks[i].innerHTML;
var newstring = str.replace(/ /g, '<span class="space"> </span>');
shadedtextblocks[i].innerHTML = newstring;
}
Update #2 - Works with background images now.
http://jsfiddle.net/37s7ex2j/
Here's an updated version that works for p and h1 tags and uses jQuery. It won't print backgrounds on top of your background image. It looks much better, but the script is a bit slower. Here's the result:
$('.shadedtext').each(function(){
//FOR P ELEMENTS
var text = $.trim($('p').text()),
word = text.split(' '),
str = "";
$.each( word, function( key, value ) {
if(key != 0) { str += " "; }
str += "<span class='shade'>" + value + "</span>";
});
$('p').html(str);
});

Choosing text in a container
In short: No you can not set the background of only the text in a div, or spesialy choose each color for each word.
What you can do is set the text of each container ofc:
<div class="class"></div>
.class {
//background, can also use rgba(0,0,0,0.5) <- semi transparent black.
background-color: white;
}
But I don't want to contain each / every word with a div or span - as that will make the total HTML coding huge...
Keeping your text inside inline-block elements will keep the selection to some what text only.
Example:
p {
background-color: rgba(5, 5, 5, 0.5);
color: white;
}
p.inline {
display: inline-block;
}
Inline
<p>Lorem ipsum dolar si amet</p>
Inline-block
<br>
<p class="inline">Lorem ipsum dolar si amet</p>

If you want something like subtitles on TV, you can add a text-shadow on your text:
.myTextClassSelector{
text-shadow: green 1px 1px, green -1px 1px, green -1px -1px, green 1px -1px;
}
<div>
<p class="myTextClassSelector">This text here</p>
And this other text here.
</div>

Related

How to add a tint to a background image with transparency in CSS

I have some content on a page that serves as a global background.
I put a sprite (div with background-image: url(...), changing frames by modifying background-position) on top of that using position: absolute. The sprite is a PNG with alpha-channel.
Now I'm trying to add some tint to that image (greenish or blueish or other).
I've studied the similar questions and apparently the only possible solutions are:
Create a div on top of the sprite with the desired color as its background-color, desired tint strength as opacity and the original sprite image as mask-image (and setting the mask-type: alpha). While it should work on paper, it doesn't in practice - this new div is just invisible :(
Use mix-blend-mode for the overlaying colored div and specify something like multiply or overlay. It produces perfect results as long as the global background is black. If it's something else - it gets included in the calculations and the overlay div modifies it as well, producing a tinted rectangle instead of tinted sprite...
Use SVG filter as described in an answer here: https://stackoverflow.com/a/30949302/306470 .
I didn't try this one yet, but it feels unnecessary complicated for this task. I'm concerned about the performance here too, will it slow down things a lot if there will be multiple tinted sprites on the screen at the same time? If anyone had experience with it - please comment here :)
Prepare a tinted version of the sprite using an invisible canvas. Sounds even more complicated, has a disadvantage of having to spend time to prepare the tinted version of the sprite, but should work as fast as the original sprite once it's prepared? Implementation should be pretty complicated though. Pure CSS solution would be much better...
Am I missing something? Are there any other options? Or should I go with #3 or #4?
Here is a working example of the outlined comment I left, hope it helps. I use a created div element to overlay on top of the image. Get the image elements position using boundingClientRect and this.width/this.height inside a for loop looping over the image elements. Set the overlay elements position to that of the image element being looped over and randomize a color using function with rgb setting alpha to 0.5.
let fgrp = document.getElementById("group");
let images = document.querySelectorAll(".imgs");
//function to randomize the RGB overlay color
function random() {
var o = Math.round,
r = Math.random,
s = 255;
return o(r() * s);
}
//function to randomize a margin for each image to show the overlay will snap to the image
function randomWidth() {
var n = Math.round,
ran = Math.random,
max = 400;
return n(ran() * max);
}
// loop through the img elements and create an overlay div element for each img element
for (let i = 0; i < images.length; i++) {
// load the images and get their wisth and height
images[i].onload = function() {
let width = this.width;
let height = this.height;
this.style.marginLeft = randomWidth() + "px";
// create the overlay element
let overlay = document.createElement("DIV");
// append the overlay element
fgrp.append(overlay);
// get the image elements top, left positions using `getBoundingClientRect()`
let rect = this.getBoundingClientRect();
// set the css for the overlay using the images height, width, left and top positions
// set position to absolute incase scrolling page, zindex to 2
overlay.style.cssText = "width: " + this.offsetWidth + "px; height: " + this.offsetHeight + "px; background-color: rgba(" + random() + ", " + random() + ", " + random() + ", 0.5); left: " + rect.left + "px; top: " + rect.top + "px; position: absolute; display: block; z-index: 2; cursor pointer;";
}
}
img {
margin: 50px 0;
display: block;
}
<div id="group">
<image src="https://artbreeder.b-cdn.net/imgs/275c7c05efca3a40e3178208.jpeg?width=256" class="imgs"></image>
<image src="https://artbreeder.b-cdn.net/imgs/275c7c05efca3a40e3178208.jpeg?width=256" class="imgs"></image>
<image src="https://artbreeder.b-cdn.net/imgs/275c7c05efca3a40e3178208.jpeg?width=256" class="imgs"></image>
</div>
Following the guide below, it is possible to at a colorful tint over a div/image using only CSS, like so:
<html>
<head>
<style>
.hero-image {
position: relative;
width: 100%;
}
.hero-image:after {
position: absolute;
height: 100%;
width: 100%;
background-color: rgba(0, 0, 0, .5);
top: 0;
left: 0;
display: block;
content: "";
}
</style>
</head>
<body>
<div class="hero-image">
<img src="https://cdn.jpegmini.com/user/images/slider_puffin_before_mobile.jpg" alt="after tint" />
</div>
<div>
<img src="https://cdn.jpegmini.com/user/images/slider_puffin_before_mobile.jpg" alt="before tint" />
</div>
</body>
</html>
Since you are trying to place it on top of an absolute position image, as the guide says, add a z-index of 1 (for example) to the :after chunk.
Edit: It might need some tweaking on the width's percentage!
Source: https://ideabasekent.com/wiki/adding-image-overlay-tint-using-css

Angular 2 multiple font colors in a textarea

I have a text area with one string binded to it. With the text color as white by default.
<textarea style="background-color: black;color:#fff;" [(ngModel)]="outputText"></textarea>
The bound string contains multiple variables.
return this.outputText = this.test1 + " test1Stat" + this.test2 + " test2Stat" + this.test3 + " test3Stat";
What I want to do is, if test1 is less than 1, it should show "test1 test1Stat" in red, while everything else is in green. Is there a way to do this?
It's not possible to color part of the text in a textarea,
However- you can try to use the 'contenteditable' property instead.
It basically turns your div into a textbox, and you can use html tags and such inside.
.greenText{
color:green;}
div{
border:black solid 1px;
padding:20px;
}
<div contenteditable="true">text text <span class='greenText'>GREEN TEXT</span> more text that you can edit</div>

Html to canvas background color wraps incorrectly

I am using html2canvas.js 0.4.1 to convert a DOM to canvas for printing. When the text has a background color on a span, and the span wraps to the next line, then the canvas version covers the whole rectangle of the 2 wrapping lines. It doesn't just cover the text. Furthermore it hides the text in the prior span.
The following fiddle demonstrates it pretty well. The 'one one' span is completely covered up by the blue background on the 'two two' span.
https://jsfiddle.net/sddah9k2/1/
css:
#content {
width:200px;
}
.select {
background-color:#3efcdb
}
html:
<div id='content'>
<span >one one one one one one </span>
<span class="select" >two two two two two two </span>
<span >three three three three three </span>
</div>
<div id="img-out"></div>
code:
html2canvas($("#content"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
// Convert and download as image
Canvas2Image.saveAsPNG(canvas);
$("#img-out").append(canvas);
// Clean up
//document.body.removeChild(canvas);
}
});
My theory is html2canvas can't tell what the bounding box of the spans are, or maybe it just doesn't support multiple rectangles as bounds.
Is there any type of CSS effect I can use on the HTML text that will render correctly in html2canvas? It doesn't have to be a background color, but I have to somehow indicate that the wrapping span is highlighted.
Canvas does not support multi line inline texts. So your libraries splits it up, but the wrapping .select box gets the dimensions like an inline-block element.
You need to split and wrap every highlighted word with a seperate span.
JS:
var $selected = $('#content.notupdated .select');
$selected.each( function() {
var $this = $(this);
var words = $this.text().split(" ");
$this.empty();
$.each(words, function(i, v) {
$this.append($("<span>").text(v + ' '));
});
});
$('#content.notupdated').removeClass('notupdated').addClass('updated');
I updated you fiddle for that: https://jsfiddle.net/sddah9k2/7/
I even updated #Kaiidos improved fiddle of yours: https://jsfiddle.net/sddah9k2/6/ (I worked primarily on that one)
I already accepted Seika85 answer since his was the first. Here is what I ended up with, retaining the original span and also to do this for every 'select' span:
link:
https://jsfiddle.net/sddah9k2/9/
js:
// Get all the select spans
$('span.select').each(function (ix, block) {
// split the text spans on word so it wraps in the same place
var txtar = $(block).text().split(' ');
// Remove the class on the outer span, but keep it intact.
$(block).removeClass('select');
$(block).html(''); // empty it
// Replace each word. Note the space before closing span!
$(txtar).each(function (ix, txt) {
$(block).append($('<span class="bg">'+txt+' </span>'));
});
});
css:
.select {
background-color:#3efcdb;
}
.bg {
background-color:#3efcdb;
}

Why isn't mix-blend-mode working on the font/text in this CSS?

I'm trying to use the CSS mix-blend-mode to make this text dodge over the background image but the css only seems to work on the div's background. I've seen it work on text before so why isn't it working here?
#draggable { mix-blend-mode: color-dodge; }
Demo: http://codepen.io/anon/pen/YyJGzo
The settings that you are using (text color and blend mode) are not noticeable
From the w3c page
10.1.8. color-burn blend mode
Darkens the backdrop color to reflect the source color. Painting with
white produces no change.
if(Cb == 1)
B(Cb, Cs) = 1
else if(Cs == 0)
B(Cb, Cs) = 0
else
B(Cb, Cs) = 1 - min(1, (1 - Cb) / Cs)
Where Cb == 1 means white in the backdrop (the text in your case), and B(Cb, Cs) = 1 means that the resulting color stays white. (Without any contribution from the background)
Try
#draggable{
color: green;
mix-blend-mode: screen;
}
or
#draggable{
color: grey;
}
demo codepen with grey text
for instance

Set the color of the text depending on the color of the background

I have a div that is colored dynamically and inside that div there is a text. I would like the color of the text will be white or black depending of the darkness of the color of the div.
So if for example the color of the div is dark brown I would like the color of the text be white. If the color of the div is yellow, I would like the color of the text be black.
How to do that with HTML/CSS/PHP?
Javier
How are you setting the colour of the Div? An extension of what Doug said...
var myDiv = document.getElementById("yourDynamicDiv");
myDiv.style.color = "black";
if you set the colour manually add that at the same time.
Rick
This function will take any hexcolor and return either white or black depending on what has more contrast.
function TextContrast($hexcolor){
$hexcolor = str_replace("#","","$hexcolor");
if(!$hexcolor){
$hexcolor = "FFFFFF";
}
$r = hexdec(substr($hexcolor,0,2));
$g = hexdec(substr($hexcolor,2,2));
$b = hexdec(substr($hexcolor,4,2));
$yiq = (($r*299)+($g*587)+($b*114))/1000;
if($yiq >= 128){
$text_color = "#000000";
}
else{
$text_color = "#FFFFFF";
}
} // end text contrast function
For your style sheet, you can change the .css extension to .php and add
.custom_div {background: #FF00FF;}
<?php TextContrast("FF00FF"); ?>
.custom_div {color: <?php echo $text_color; ?>
Ok so, will the colors be pre-determined, or the user will generate it? If you're going with the predetermined colors, you can set classes for the parent and the child can now where it is via css and adjust accordingly. Below is an example on how.
HTML
<div class="parent">
<div class="child"> Enter Content Here</div>
</div>
CSS
.black-bg {
background:#000000;
}
.black-bg div {
color:#FFFFFF;
}
.white-bg {
background:#FFFFFF;
}
.white-bg div {
color:#000000;
}
Everytime you change the class on the parent, it will force the browser to re-render the area, hence enabling dynamic styling.
I don't know php, but you can do it in JS like this:
JS (jquery)
if ( x === condition-1 ) {
$(".parent").addClass(".black-bg");
} else if ( x === condition-2 ) {
$(".parent").addClass(".white-bg");
}