Determine Whether Element Has Fixed or Percentage Width Using JavaScript

Determine whether element has fixed or percentage width using JavaScript

It can be done. Looking at this question (Why does getComputedStyle return 'auto' for pixels values right after element creation?) gives us the hint.

If you set the element's style to display = none and then call getComputedStyle you will get the calculated value (percentage width or 'auto' or whatever the stylesheets apply to the element) instead of the pixel width.

Working code
jsfiddle https://jsfiddle.net/wtxayrnm/1/

function getComputedCSSValue(ele, prop) {
var resolvedVal = window.getComputedStyle(ele)[prop];
//does this return a pixel based value?
if (/px/.test(resolvedVal)) {
var origDisplay = ele.style.display;
ele.style.display = 'none';
var computedVal = window.getComputedStyle(ele)[prop];
//restore original display
ele.style.display = origDisplay;
return computedVal;
} else {
return resolvedVal;
}
}

It should be noted that this will cause the layout to be re-rendered but, depending on your situation, it's probably a simpler solution than traversing all the stylesheet rules or cloning the element (which can cause some cascading rules to not be applied).

How to set width of a div in percent in JavaScript?

document.getElementById('header').style.width = '50%';

If you are using Firebug or the Chrome/Safari Developer tools, execute the above in the console, and you'll see the Stack Overflow header shrink by 50%.

How to set a div percentage width with a fixed position based on the parent element

The only way to do this is by setting the .details width with JavaScript. Try this:

$(window).scroll(function(){
if($(window).scrollTop() >= 90){
$('.details').css({position:'fixed',right:40,top:40});
} else {
$('.details').css({position:'relative',right:0,top:0});
}
});

// set the width of the details div when window resizes
window.addEventListener('resize', function(){

var $el = $('.details')

$el.width( $el.parent().outerWidth() * .25 )

})

Here's a crude example

Position fixed element with percentage width relative to container

You can get the effect that you want as follows.

Your HTML snippet is good as is:

<div id="content">
<section>
<h1>Heading 1</h1>
<p>...</p>
</section>
<section>
<h1>Heading 2</h1>
<p>...</p>
</section>
</div>

and the CSS is good but just requires some explanation:

#content {
overflow: visible; /* default, but important to notice */
}

section {
float: left;
width: 25%;
}

h1 {
position: fixed;
width: 25%;
background: #00FF00;
text-align: center;
}

and the demo fiddle: http://jsfiddle.net/audetwebdesign/4zLMq/

How This Works

Your #content block takes up the remaining width to the right of your 200px left floated sidebar.

Within #content, you have two left-floated section elements that take up 25% of the parent container, which in this case, is the width of the view port panel.

Your child h1 elements have position: fixed, which means that their width of 25% is also computed based on the width of the viewport (not #content).

Case 1
If you want h1 and #content to have the same width, they need to have the same relative (25%) computed from the same containing block (view port in this case).

However, the value of 25% is not 25% of the remaining space after you account for the floated sidebar. However, maybe you can live with this.

Case 2
You could make the width values a bit easier to determine if you set the sidebar width to be a relative value. Using mixed units is always an issue.

Get element CSS property (width/height) value as it was set (in percent/em/px/etc)

Good news everyone! There seems to be a CSS Typed OM on his way in the w3c drafts.

Fast reading this document, it seems that the goal of this maybe to-be specification, is to ease the access of CSSOM values from javascript.

The really important part of this for us here is that we will have a CSSUnitValue API, which will be able to parse CSS values to an object of the form

{
value: 100,
unit: "percent", // | "px" | "em" ...
type: "percent" // | "length"
}

And add a computedStyleMap() method, to the Element interface, from which we will be able to get the values actually applied on our elements.

As of today, only Chrome implements it (since 66).

(() => {  if (!Element.prototype.computedStyleMap) {    console.error("Your browser doesn't support CSS Typed OM");    return;  }  document.querySelectorAll('.test')    .forEach((elem) => {      let styleMap = elem.computedStyleMap();      const unitvalue = styleMap.get('width');      console.log(elem, {        type: unitvalue.type(),        unit: unitvalue.unit,        value: unitvalue.value      });    });
/* outputs
<div class="b test">first</div> { "type": { "length": 1 }, "unit": "px", "value": 100 } <div id="a" class="a test">second</div> { "type": { "percent": 1 }, "unit": "percent", "value": 50 }
*/
})();
div.test {  width: 100px; }x,div#a {  width: 50%; }.a {  width: 75%; }
<div class="b test">first</div><div id="a" class="a test">second</div>

Percentage width for fixed elements?

I set an absolute width using javascript to detect the computed width of #first.



Related Topics



Leave a reply



Submit