Use external font for inline CSS in React.js - javascript

Hello there everybody,
I am trying to make a to-do list in react, and in there, I want to change the font to something external, like Montserrat or Roboto. Unfortunately, I am using CSS in an inline way. I am not sure how to add the external CSS. Usually, I copy and paste an #import snippet, which looks like this:
#import url('https://fonts.googleapis.com/css?family=Roboto');
Here is my code for my TodoItem(The file for the individual todo item)
import React from 'react'
function TodoItem(){
const styleSpan = {
fontSize:50,
fontFamily:"Roboto",
borderRadius:10
}
const styleCheckbox = {
width:50,
height:50,
marginRight:50,
backgroundColor:"#edc2d6",
}
return(
<div>
<input type = "checkbox" style = {styleCheckbox}></input>
<span style={styleSpan}>Todo item here</span>
</div>
)
}
export default TodoItem
to use inline CSS, you must put your style options in an object. This can work when you have two correlating values, but almost impossible for single values.
How can I add an external font when coding for inline CSS?

How can I add an external font when coding for inline CSS?
You can try something like this -
<div>
<style
dangerouslySetInnerHTML={{
__html: `
#font-face {
font-family: 'AdamGorry-Lights';
src: url(url-to-font) format('woff2');
font-weight: 300;
font-style: normal;
}
`,
}}
/>
<input type="checkbox" style={styleCheckbox}></input>
<span style={styleSpan}>Todo item here</span>
</div>
This allows you to use it in styles as
const styleSpan = {
fontSize: 50,
fontFamily: 'AdamGorry-Lights',
borderRadius: 10
}

You can import the css in the parent css file & change the font family.
Have created a DEMO. In this demo I have imported the css in the style.css file and have changed the font-family to Roboto

Related

How can I style a component whose class changes based on a `use` directive in Svelte?

I am creating a directive which adjusts the class of the element that it is applied to. However, the styles for that class do not apply when the class changes. For instance:
Form.svelte
<form id='sign-in' use:delayed={ handleSubmit }>
<label for='sign-in-name'>Your Name</label>
<input required id='sign-in-name' type='text' />
<input type='submit' value='Sign In' />
</form>
<style>
form {
display: block;
}
form.submitting {
display: none;
}
</style>
Delayed.js
export default function(node, action) {
node.addEventListener('submit', async function(event) {
event.preventDefault()
const originalClass = node.className
node.className = `${ originalClass } submitting`
await action()
node.className = originalClass
})
}
In this case, the class will change successfully in the DOM, but the form will still display. The form.submitting style doesn't even make it into the CSS generated by Svelte.
I know that I can work around this using a global stylesheet, but I'm curious why the scoped styles don't apply and if there's a way to make it work that way.
This works, but it feels hacky.
<style>
form {
display: block;
}
:global(form.submitting) {
display: none;
}
</style>
Svelte compiler removes unused CSS rules, that is rules with selectors that do not match in the markup of the component. You should have a compiler warning "Unused CSS selector" about that. And since the compiler can't see dynamically added classes, your form.submitting selector is removed.
The solution is indeed to make your dynamic selector :global(...).
If you want your style to only apply in the scope of this component and its children, you need a wrapping element that you can reference like such:
<div>
<form>...</form>
</div>
<style>
div :global(form.submitting) { ... }
</style>
Svelte will scope the div part of the selector to the current component, effectively meaning that the :global(...) part will only apply to the form inside a <div> inside this component.

Changing text size via button

could someone please explain to me, why id of "he" changes the font size, however id "clanky" stays the same.
<h1 id="he">Zoznam článkov / Article List</h1>
<main id="clanky"></main> //there are articles plugged in there in different function
function myFunction() {
document.getElementById("he").style.fontSize = "90px";
document.getElementById("clanky").style.fontSize = "90px";
}
I tried just changing the color to see if it works overall and yes, the color does change in both of them. Anyone might have an idea, what is blocking the "clanky" font size to be changed?
In order to increase every elements font size you will have to have a root/default set somewhere. This will usually just be in the styling of your <body>.
Example (CSS):
body {
font-size: 16px;
}
Now that there is a 'default' size, you can go to which ever element you want and use the rem and em units rather than px.
So instead of typing 16px on every element, you can now do 1em.
This means that so when you change the root size, every other element that uses em or rem should be effected.
(Note: the button's font size won't change in this snippet. If you would like that to happen you will have to add font-size: 1em; in CSS to your button tag.)
Read more about em and rem units here.
document.getElementById('increaseFont').onclick = function () {
var body = document.getElementsByTagName("BODY")[0];
body.style.fontSize = "22px"; // - Whatever you want the font the increase to.
};
document.getElementById('defaultSize').onclick = function () {
var body = document.getElementsByTagName("BODY")[0];
body.style.fontSize = "16px"; // -- THE DEFAULT FONT SIZE IN CSS
};
body {
font-size: 16px;
}
<h1>I am a heading!</h1>
<p>I'm just a small paragraph...</p>
<button id="increaseFont" type="button">
Increase all fonts
</button>
<button id="defaultSize" type="button">
Default font size
</button>
It does. You didn't include enough, but my guess is that you're changing the div, but there are tags inside the div that the CSS is controlling.
https://jsfiddle.net/24emLxn7
<h1 id="he">Zoznam / Article List</h1>
<main id="clanky">blah blah</main>
push me 1
push me 2
As you said that the article is plugged there from another place, there are inline font-size in that article that you can not override by setting font-size on parent element. Thats all.
Working fine. Maybe you have some other event on div inside the main tag.
<h1 id="he">Zoznam clánkov / Article List<br>Hello</h1>
<main id="clanky"></main>
<input type='button' value="Change Font Size" onclick='myFunction();'>
function myFunction() {
document.getElementById("clanky").innerHTML='Hello';
document.getElementById("he").style.fontSize = "90px";
document.getElementById("clanky").style.fontSize = "90px";
}

Asp.Net MVC overriding Class CSS

I have an H1 tag and inside that, there is anchor tag which is generating from the code
<div class=".slide-title">
<H1>
#RenderLinkTracking(m => m.btn, Model.bTnTitle)
</H1>
</div>
The RenderLinkTracking creates anchor tag
Image Title
CSS of the anchor tag is
.slide-title a
{
color : red;
}
I am trying to override the CSS of the anchor tag. This is how I am doing and working fine
<style>
#if (Model.Param.H1CSS!= null)
{
<text>
.slide-title a
{
#Html.RenderCSSAndJSAttributes(Model.Param.H1CSS).ToString().Replace("style=","")
}
</text>
}
</style>
The method Html.RenderCSSAndJSAttributes is generating a style color:#001595 !important;font-family:Book Antiqua !important;Text-align:10px;Text-align:Center
Is there any better way to override the class CSS or append the inline CSS using jquery? Any suggestion would be appreciated.
Thanks in advance
Change custom helper could look like this:
namespace System.Web.Mvc {
public static class HtmlHelperExtensions {
public static MvcHtmlString RenderLinkTracking(this HtmlHelper helper, string url, string linkText, string style) {
//...
return MvcHtmlString.Create(String.Format("<a href='{0}' style='{1}'>{2}</a>", url, style, linkText));
}
}
}
So You can pass style for each custom link like this:
<div class=".slide-title">
<H1>
#RenderLinkTracking(m => m.btn,Model.yourUrl, Model.bTnTitle, Model.Param.H1CSS)
</H1>
</div>
Simple Solution is by creating another CSS Style for the anchor hierarchy .slide-title h1 a
.slide-title a
{
color:#001595!important;
}
.slide-title h1 a
{
color: green!important;
}
<div class="slide-title">
<h1>
H1 Anchor
</h1>
Simple Anchor
</div>

Adding icons to pseudo elements

I'm trying to add icons to my navigation (which dynamically changes) via JavaScript.
Here is my code (or JSFiddle):
var icon = document.querySelector('#icon');
icon.setAttribute('data-icon', '†');
#icon:after {
content: attr(data-icon);
}
<div id="icon" data-icon="">
Icon
</div>
But it is not working, why? When tried to edit data-icon attribute manually, icon appears. Otherwise just unicode of icon.
HTML entities don't have any meaning in CSS. If you want to follow that path you need to decode it first:
var icon = document.querySelector('#icon');
var tmp = document.createElement("span");
tmp.innerHTML = '†';
icon.setAttribute('data-icon', tmp.innerText);
#icon:after {
content: attr(data-icon);
}
<div id="icon" data-icon="">
Icon
</div>
... or, alternatively, just type character as-is (as long as your application is written in UTF-8):
var icon = document.querySelector('#icon');
icon.setAttribute('data-icon', '†');
#icon:after {
content: attr(data-icon);
}
<div id="icon" data-icon="">
Icon
</div>
Last but not least, CSS also accepts escape sequences but you need to use the appropriate syntax. This approach, however, does not seem to work for your specific character:
var icon = document.querySelector('#icon');
// Brackets added for visibility, not part of the syntax
icon.setAttribute('data-icon', '(\u0086)(\u2020)');
#icon:after {
content: attr(data-icon);
}
<div id="icon" data-icon="">
Icon
</div>
I presume it's related to the fact that U+2020 'DAGGER' (that works fine) is a regular character but the one you're using U+0086 'START OF SELECTED AREA' (which doesn't show) is a control character. As you mention in a follow-up comment, you're using FontAwesome and such libraries provide custom fonts that map certain code points to display icons (though they normally use private areas to avoid conflicts).
That is obviously because setAttribute is escaping your special characters...and anyway you need to use CSS encoded icons and not an HTML entity. use this convertor:
† → \0086
I would suggest working with meaningful names instead of hard-coded writing the icon's code into an attribute.
For example:
var icon = document.querySelector('#icon');
icon.setAttribute('data-icon', 'icon-heart');
[data-icon=icon-heart]{
content:'\2764';
}
(better that all your icons elements will have a shared class which shared properties)
Encoding minefield
See this StackOverflow answer for more details.
Answer updated (see comments and edits).
In short, I recommend using the character instead of any method of encoding it. It will be vital in this case that your HTML files are correctly encoded and that they properly inform browsers what the encoding is.
var js = document.querySelectorAll( ".js" );
js[ 0 ].setAttribute( "data-icon", "\u0086" );
js[ 1 ].setAttribute( "data-icon", "†" );
.css:after {
content: "\86";
color: red;
}
.css.char:after {
content: "†";
color: blue;
}
.data:after {
content: attr( data-icon );
}
.js:after {
content: attr( data-icon );
}
.red:after {
color: red;
}
.blue:after {
color: blue;
}
<div class="css">hard coded css content</div>
<div class="css char">hard coded css content char</div>
<br>
<div class="data red" data-icon="†">hard coded data-icon</div>
<div class="data blue" data-icon="†">hard coded data-icon char</div>
<br>
<div class="js red">data-icon by js</div>
<div class="js blue">data-icon by js char</div>

change css with knockoutjs

Lets say that I have a div with a background color of #333333, and I have an input field where the user can input their own hex value, ex: #000000, and then I want the div's background color to change to #000000 on the fly....
example:
HTML:
<div class="mydiv"></div>
css:
<style type="text/css">.mydiv { background-color:#333333; }</style>
Then when the user changes the value via an input type="text" field, when the CSS should change in the style="text/css" block.
How do I make that binding?
I can't use the in my style block, because that is not valid CSS, and I don't want to do it on my like and then insert the style here... So again, I want to change the CSS in my style block, and not add a style to my div element.
Sort of like this where they update it on the fly; http://css3gen.com/box-shadow/
When you change something, the CSS behind changes, so that you can preview your element on the fly.
Use style binding
<div data-bind='style: { "backgroundColor": CustomBGC }'>
http://jsfiddle.net/nyothecat/jKysB/3/
Edit:
Since you want to update the style, you can make use of the cascading style sheet.
Define a class with init color, then create a style tag with a text binnding. Fill this one with your new color.
In your css file:
.myClass { background-color: #f00 }
Make sure to put your css file before the following
<div id="koRoot">
<div class="myClass">
<input type='text' data-bind="value: customColor" />
</div>
<style data-bind="text: myObservableStyle(customColor)"></style>
</div>
And the javascript:
$(document).ready(function () {
var ViewModel = {
customColor: ko.observable("#f00"),
myObservableStyle: function (obs) {
return ".myClass { background-color: " + obs() + " }";
}
}
ko.applyBindings(ViewModel, document.getElementById("koRoot"));
});
http://jsfiddle.net/k97ZZ/1/
pseudohtml :
<input type="text" data-bind="value:userInput">
pseudoscript:
var MyModel=function(data){
var self=this;
self.userInput=ko.observable('#333333');
self.computedCss=ko.computed(function(){
//appends Style block to head everytime userInput changes
appendal="<style>.myClass { background-color: "+self.userInput()+";!important}</style>";
$('head').append(appendal);
}
}
myModel = new MyModel({});
ko.applyBindings(myModel);
You can use the style binding along with the value binding
<input data-bind="value: inputColor" />
<div data-bind="style: { color: inputColor()}">
Something
</div>
var viewModel = {
inputColor: ko.observable()
};
Edit
Since you want to change the style element itself use the text binding on style tag. One thing to remember that entire style will be changed so you will have to maintain valid css rules before updating the element.
<style data-bind="text:inputColor"></style>
You might want to subscribe to the inputColor observable so you can change the input to valid css before populating the style element.
This question might be relevant.
You can use virtual if binding
<style type="text/css">
<!-- ko if: someExpression -->
.mydiv { background-color:#333333; }
<!-- /ko -->
<!-- ko if: !someExpression -->
.mydiv { background-color:#000000; }
<!-- /ko -->
</style>

Categories

Resources