Reputation: 1081
I want to style the :host{}
, of a custom Polymer element, with Javascript (dynamically). The property I want to style is the "line-height", which will vary depending on the user's screen size (the text will always be on one line).
In an attempt to find a sulotion I have used two different methods:
The first is with normal jquery:
<dom-module is="custom-element">
<template>
<style>
:host {
position: relative;
display: inline-block;
min-width: 5.15em;
min-height: 2em;
padding: 0.5em;
background: transparent;
font-size: 1.3em;
outline: none;
cursor: pointer;
color: #ABCFCA;
text-transform: uppercase;
text-align: center;
overflow: hidden;
}
</style>
<content></content>
</template>
<script>
Polymer({
is: "custom-element",
properties: {
},
ready: function() {
$(this).css("line-height", $(this).height() + "px");
}
});
</script>
The second method I tried is using Polymer's custom css properties:
<dom-module is="custom-element">
<template>
<style>
:host {
position: relative;
display: inline-block;
min-width: 5.15em;
min-height: 2em;
padding: 0.5em;
background: transparent;
font-size: 1.3em;
outline: none;
cursor: pointer;
color: #ABCFCA;
text-transform: uppercase;
text-align: center;
overflow: hidden;
line-height: --dynamic-line-height;
}
</style>
<content></content>
</template>
<script>
Polymer({
is: "custom-element",
properties: {
},
ready: function() {
this.customStyle['--dynamic-line-height'] = $(this).height();
this.updateStyles();
}
});
</script>
In the first method (plain jquery) when inspecting the element with Chrome's Element Inspector the line-height
property isn't even added/set, and the text remains at the default vertical position
The second method ends up the same as the first method (no change/result in the element's style)
It should be noted that console.log($(this).height());
produces the expected result of 32px
(on my screen)
It would be awesome if someone can help me either fix/edit any of my existing methods or provide me with a method that they have used/is documented somewhere.
Thank You.
Upvotes: 3
Views: 1516
Reputation: 658225
Your CSS in the 2nd example only uses a CSS variable but doesn't declare one. Declare one first like:
<style>
:host {
--dynamic-line-height: 1px;
....
line-height: var(--dynamic-line-height);
}
</style>
...
ready: function() {
var height = Polymer.dom(this).node.offsetHeight + 'px';
this.customStyle['--dynamic-line-height'] = height;
this.updateStyles();
}
See also Changing CSS variables via JS in Polymer
Upvotes: 1