0

Having a custom LWC now I need to make it responsive, so I'm adding a media query @media screen and (max-width : 480px)

This doesn't work, If I change max-width to max-device-width it works, but I want to use only max-width as the max-device-width will soon be deprecated.

Any help on how to use media queries on LWC ?

1 Answer 1

3
  1. Below is how you can target p element and max-width or min-width:
@media screen and (min-width: 900px) {
    p {
        background: black;
        color: white;
    }
}

@media screen and (max-width: 900px) {
    p {
        background: blue;
        color: white;
    }
}
  1. It is preferable to use device-size in LWC. Below is how it behaves:
  • size is mandatory when you want custom responsive design by defining large, mediu and small.
  • size starts from 0 width.
  • When you just give size and medium-device-size, size will be taken for 0 to medium width. Sample is with small or large.
  • small is actually the horizontal view for almost all mobiles - this is very important point. Therefore size should be maximum parts always to accommodate mobile vertical view.

Below are the examples:

  1. Consider below code:
<lightning-layout multiple-rows>
        <lightning-layout-item size="4" small-device-size="12">
            ... content ...
        </lightning-layout-item>
        <lightning-layout-item size="4" small-device-size="12">
            ... content ...
        </lightning-layout-item>
        <lightning-layout-item size="4" small-device-size="12">
            ... content ...
        </lightning-layout-item>
    </lightning-layout>

This will render 3 columns in mobile vertical view and single column in mobile horizontal view. So, you need size to be maximum parts of all device sizes always - which means 12 in this case.

  1. For below example:
<lightning-layout-item size="12" large-device-size="4">
    ... content ...
</lightning-layout-item>
<lightning-layout-item size="12" large-device-size="4">
    ... content ...
</lightning-layout-item>
<lightning-layout-item size="12" large-device-size="4">
    ... content ...
</lightning-layout-item>

For big screens, you get 3 columns and for any device less it will be single column

  1. For below example:
<lightning-layout-item size="12" large-device-size="4" medium-device-size="6" small-device-size="12">
    ... content ...
</lightning-layout-item>
<lightning-layout-item size="12" large-device-size="4" medium-device-size="6" small-device-size="12">
    ... content ...
</lightning-layout-item>

This is straight forward - mobile vertical or horizontal view will have single columns. Medium devices like pads will have 2 columns and desktops will have 3 columns.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .