Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 419
Chris GW Green Avatar asked Apr 18 '13 10:04

Chris GW Green


People also ask

What are media queries explain with example?

A media query is an HTML/CSS functionality that allows the content of a Web page to adapt to the type of media that the page is being rendered in, such as a computer screen or that of a phone or tablet.

What does @media do in CSS?

The @media CSS at-rule can be used to apply part of a style sheet based on the result of one or more media queries. With it, you specify a media query and a block of CSS to apply to the document if and only if the media query matches the device on which the content is being used.

What is the benefit of using Programmatical media query Usemediaquery instead of CSS?

Flexibility: You can programmatically incorporate media queries into your JavaScript code so that they are only triggered at the onset of a particular event or when certain conditions are met. With a CSS3-only approach, the changes described by a media query go into effect for every screen resize event.


1 Answers

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.

like image 97
nickhar Avatar answered Oct 14 '22 01:10

nickhar