Chris GW Green
Chris GW Green

Reputation: 1199

Dynamic Media Queries

I'm currently using a js/jq resize event to apply a css rule to a horizontal menu (of variable width) when it becomes too large for the screen. The menu however wraps momentarily before the new rule is applied.

Ideally I'd like to measure the menu width and change the break point of a media query!

@media screen and (min-width: THIS-VALUE){
    New Rules
}

Is this possible??

Thanks in advance.

Chris GW Green

Upvotes: 7

Views: 9354

Answers (3)

grandinero
grandinero

Reputation: 1225

You can accomplish this with matchMedia.

I gave a usage example in this answer.

I assume you only need to measure the menu width once. This solution should accommodate that easily.

Upvotes: 0

nickhar
nickhar

Reputation: 20823

You can create a media query rule programatically - activated by measuring the width of your menu (using js/jQuery):

  document.querySelector('style').textContent +=
     "@media screen and (min-width:400px) { div { color: red; }}"

Media queries aren't designed to activate on the changing width of an element within a page or screen though - more by changes to the viewport/window itself and other factors. (A full list can be found here)

You've not posted your menu code so it's hard to understand the 'wrapping' you're experiencing, but if your horizontal menu is going 'off screen', then you might be better off setting the menu as a percentage(%) width of viewport and using a series of media queries that re-draw the menu and change/remove child elements etc at certain screen widths.

Upvotes: 4

David Fariña
David Fariña

Reputation: 1594

Try meta tags, instead of media queries. In meta tag you can use also the min-width property.

As if meta is a html tag you can then change the value how you like it:

var element = document.getElementByTagName('meta')[0];

element.setAttribute('content','Value');

Example use of meta tag

Upvotes: 0

Related Questions