Carryonplease
Carryonplease

Reputation: 66

Why is this flexbox media query not working?

New to this, be nice :) (and pardon the sloppy code) I did search and already have found help here. Been helping redo an ebay store at work. Trying to get this media query to work with flexbox. From what I understand, a media query can't be used inline, but can be used inside style tags inside the head without having to link to external css.

here's a codepen of the layout. I've even tested other media queries, (there is one in there now) and they work. But I want the flex items to wrap to the full 100% width once screen size is smaller, and it won't seem to work.

I know I'm targeting the right rule because it was tested without the query:

.flex-item {
   width: 100%;
}

and it does what I want it to do...How come the background color query works inside the HTML, while the flex query does not?

I'm sure it's something dumb.

https://codepen.io/pmendola/pen/MXjwza

(i removed some of the code for simplicity - there are only a few flex rules in use, right at the top of the css)

Upvotes: 2

Views: 6450

Answers (3)

user8476972
user8476972

Reputation: 1

Make sure your .flex-item is not allowed to shrink

.flex-item {
    width: 100%;
    flex-shrink: 0;
}

The default behavior of the items in a flex container is to shrink.

The flex-shrink property changes the shrink priority of the items, by setting it to 0 that item will not shrink.

Upvotes: 0

Joseph Marikle
Joseph Marikle

Reputation: 78540

This is a specificity issue. Media queries do not add specificity to a query, so

@media screen and (max-width: 480px) {
    .flex-item { ...

and

.flex-item { ...

have equal importance. The result is that the one that is declared last in your stylesheet (style tag in this case) is used. The later declaration overrides the first one.

You can correct this by placing your media query rule further down in the styles than where the rule that isn't in a media query is declared. Think of it as your media specific styles overriding the defaults. As such they need to come later in the styles.

Upvotes: 4

Evans
Evans

Reputation: 651

Adding the !important to the flex definition will fix this for you.

@media screen and (max-width: 480px) {
  body {
    background-color: yellow;
    }
    .flex-item {
      width: 100% !important;
      margin: 0 auto;
    }     
}

what does this mean?

You need a more specific style that only is defined for mobile screens and is attached to the element. More Info

Upvotes: 2

Related Questions