英文:
Mui sx styling ONLY at certain breakpoint
问题
我正在将一些旧的 MUI 样式转换为使用 sx
属性,并注意到你可以使用 sx = {{ someCssProp: { xs: ..., md: ...
等不同断点来指定样式。
我之前一直在一些样式中使用 theme.breakpoints.only
,在阅读了官方文档关于断点使用的部分后,听起来在 sx
中使用 xs, md, ...
只会应用 theme.breakpoints.up
... 这意味着如果我想要只在 xs
断点上应用样式,像这样做:
<Box sx={{background: {xs: 'blue'}}}>Some content</Box>
将意味着 Box
从 xs
断点开始具有蓝色背景...
是否有一种方法可以复制我 .only
的用例呢?
英文:
I am converting some old mui styling to use the sx
attribute and have seen that you can specify styles as different breakpoints with sx = {{ someCssProp: { xs: ..., md: ...
etc.
I have previously been using theme.breakpoints.only
for some of my stylings and after reading the official docs on breakpoint usage, it sounds like the xs, md, ...
usage within sx
will only apply theme.breakpoints.up
... meaning that if I want styling only at xs
, doing something like:
<Box sx={{background: {xs: 'blue'}}}>Some content</Box>
Will mean that the Box
has a blue background from xs...
Is there a way in which I can replicate my .only
use case?
答案1
得分: 2
As you've noticed, the breakpoints object syntax only applies going "up" (larger) per the docs:
Breakpoints as an object
The first option for breakpoints is to
define them as an object, using the breakpoint values as keys. *Note
that each property for a given breakpoint also applies to all larger
breakpoints in the set. For example,width: { lg: 100 }
is equivalent
totheme.breakpoints.up('lg')
.
That does mean that with your current code the Box
has a blue background from xs
up.
Since you're trying to define styles for only
one particular breakpoint, you will need to define your own behavior, using the theme breakpoints helper functions, in the sx
prop. For example:
<Box
sx={(theme) => ({
[theme.breakpoints.only("sm")]: {
backgroundColor: 'blue'
}
})}
>
Some content
</Box>
Working CodeSandbox: https://codesandbox.io/s/mui-breakpoints-in-sx-only-yr7h42?file=/demo.tsx
英文:
As you've noticed, the breakpoints object syntax only applies going "up" (larger) per the docs:
> Breakpoints as an object
>
> The first option for breakpoints is to
> define them as an object, using the breakpoint values as keys. Note
> that each property for a given breakpoint also applies to all larger
> breakpoints in the set. For example, width: { lg: 100 }
is equivalent
> to theme.breakpoints.up('lg')
.
That does mean that with your current code the Box
has a blue background from xs
up.
Since you're trying to define styles for only
one particular breakpoint, you will need to define your own behavior, using the theme breakpoints helper functions, in the sx
prop. For example:
<Box
sx={(theme) => ({
[theme.breakpoints.only("sm")]: {
backgroundColor: 'blue'
}
})}
>
Some content
</Box>
Working CodeSandbox: https://codesandbox.io/s/mui-breakpoints-in-sx-only-yr7h42?file=/demo.tsx
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论