gpt4 book ai didi

css - 媒体查询没有正确触发值?

转载 作者:行者123 更新时间:2023-11-27 23:04:23 24 4
gpt4 key购买 nike

我开始用styled-components 编写自己的设计系统| .但我正在努力让我的组件响应。

// Container.tsx
import React from 'react'
import styled from 'styled-components'

import { media } from '../utils/mediaQuery'

export const StyledContainer = (isFluid: boolean) => {
return styled(
({ element: Component, containerRef, ...props }) => {
console.log(isFluid)
return (
<Component ref={containerRef} {...props}>
{props.children}
</Component>
)
}
)`
width: 100%; /* Fix component tight to center*/
margin-right: auto;
margin-left: auto;
padding-right: ${({ theme }) => theme.container.paddingX}rem;
padding-left: ${({ theme }) => theme.container.paddingX}rem;

${isFluid ? '' : media.xl`max-width: 1040px;`}
${isFluid ? '' : media.lg`max-width: 960px;`}
${isFluid ? '' : media.md`max-width: 720px;`}
${isFluid ? '' : media.sm`max-width: 576px;`}
`
}

type CProps = {
fluid?: boolean
element?: React.Component | string
children: React.ReactNode | React.ReactNode[]
}

const Container = React.forwardRef(
(props: CProps, ref: React.Ref<HTMLElement>) => {
const { fluid = false, children, element = 'div' } = props

const BaseContainer = StyledContainer(fluid)

return (
<BaseContainer element={element} containerRef={ref}>
{children}
</BaseContainer>
)
}
)

export default Container
// ../../utils/mediaQuery
import {
css,
SimpleInterpolation,
CSSObject,
FlattenSimpleInterpolation,
} from 'styled-components'


export const breakpoints: { [key: string]: number } = {
xl: 1200,
lg: 992,
md: 768,
sm: 576,
xs: 376
}

export const media = Object.keys(breakpoints).reduce(
(
accumulator: {
[key: string]: (
styles: CSSObject | TemplateStringsArray,
...interpolations: SimpleInterpolation[]
) => FlattenSimpleInterpolation
},
label: string
) => {
const size = breakpoints[label]

Object.assign(accumulator, {
[label]: (
styles: CSSObject | TemplateStringsArray,
...interpolations: SimpleInterpolation[]
) => css`
@media screen and (min-width: ${size}px) {
${css(styles, ...interpolations)}
}
`
})

return accumulator
},
{}
)

一切正常。所有 CSS 都被捆绑到分块文件中,控制台上没有出现错误或错误。我的预期结果是媒体查询值的顺序,该组件的 max-width 跟随屏幕尺寸。但我的实际结果是 @media screen and (min-width: 576px) {...},它是从 ${isFluid ? '' : media.sm`max-width: 576px;`},覆盖其他查询。知道发生了什么事吗?

最佳答案

尝试颠倒媒体查询定义的顺序:

${isFluid ? '' : media.sm`max-width: 576px;`}
${isFluid ? '' : media.md`max-width: 720px;`}
${isFluid ? '' : media.lg`max-width: 960px;`}
${isFluid ? '' : media.xl`max-width: 1040px;`}

那么生成的 CSS 将是:

media screen and (min-width: 576px) {...}

media screen and (min-width: 720px) {...}

media screen and (min-width: 960px) {...}

media screen and (min-width: 1040px) {...}

对于 CSS 媒体查询,您需要首先定义最小的 min-width

而在您最后设置 min-width: 576px 之前,这意味着任何高于 576px 的屏幕都会采用该样式。

Stackoverflow answer解释原因。

关于css - 媒体查询没有正确触发值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58811040/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com