最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to append CSS from a variable in CSS or HTML file? Angular 4+ - Stack Overflow

programmeradmin0浏览0评论

Is that possible to append CSS from a variable. for example

var myHtml = "<div>My example html</div>";

// in html i can do this

<div [innerHTML]="myHtml"></div> 

But what if I have CSS stored in variable. like below:-

var myCss = ".exampleClass {margin: 0;width: 100%;}";

How can I add this css variable in my CSS file OR in HTML as a working css?

I'm using Angular 4+ but even JavaScript solution also appreciated.

Is that possible to append CSS from a variable. for example

var myHtml = "<div>My example html</div>";

// in html i can do this

<div [innerHTML]="myHtml"></div> 

But what if I have CSS stored in variable. like below:-

var myCss = ".exampleClass {margin: 0;width: 100%;}";

How can I add this css variable in my CSS file OR in HTML as a working css?

I'm using Angular 4+ but even JavaScript solution also appreciated.

Share Improve this question asked Apr 1, 2018 at 10:27 RajnishCoderRajnishCoder 3,7357 gold badges21 silver badges36 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

You can simply insert a new <style> tag into your page using JavaScript:

var myCss = ".exampleClass {margin: 0;width: 100%;color:blue}";

var style = document.createElement("STYLE");
style.innerText = myCss;
document.body.appendChild(style);
<div class="exampleClass">Lorem ipsum</div>

Try: <div [style.width.%]="WidthValue" [style.marginTop.px]="marginTopValue"></div>

where, in *.ts file, you are having value in a variable

WidthValue: number = 100;
marginTopValue: number = 0;

Adding one more way,

<div [ngStyle]="styleObject"></div>

where,

styleObject = {
  'width': '100px',
  'margin-top': '10px'
}
发布评论

评论列表(0)

  1. 暂无评论