CSS在100%宽度的父级中使兄弟姐妹的子级具有相同的宽度和高度(正方形)



我有一个宽度为";100%";(不是屏幕宽度(,我希望每个孩子都有相同的宽度和高度。

我的代码是:

<View style={styles.container}>
<View style={styles.item} />
<View style={styles.item} />
<View style={styles.item} />
<View style={styles.item} />
</View>
const styles = StyleSheet.create({
container: {
width: "100%",
flexDirection: "row",
alignItems: "center",
},
item: {
width: 75,
height: 75,
marginRight: 10,
backgroundColor: "red",
},
});

但这并不是对所有设备都有反应(在小服务中,一些孩子会离开屏幕(。。。还有别的办法吗?

谢谢。

container: {
flexDirection: "row",
alignItems: "center",
},
item: {
flex: 1,
aspectRatio: 1,
backgroundColor: "red",
},

对于你的情况,诀窍是aspectRatio。只需让每个孩子弯曲:1,但纵横比为1,使他们变平方。

百分比宽度

可能有很多方法可以做到这一点,但首先想到的是将宽度设置为百分比。这将使项目成为父项的百分比。

item: {
width: '30%',
height: 75,
marginRight: 10,
backgroundColor: "red",
}

如果你需要更灵活的东西,你可能想研究响应式设计,并为不同的屏幕大小设置断点。

柔性包裹

如果您希望内容保持固定大小,可以将其包装在容器中。对于不同的屏幕大小,一行中的框可能比另一行中多。

你可能需要改变一些造型,但包装看起来像这个

<View style={styles.container}>
<View style={styles.item} />
<View style={styles.item} />
<View style={styles.item} />
<View style={styles.item} />
</View>
const styles = StyleSheet.create({
container: {
width: "100%",
justifyContent: 'space-between',
flexDirection: "row",
alignItems: "center",
flexWrap: 'wrap',
},
item: {
width: 75,
height: 75,
marginRight: 10,
backgroundColor: "red",
},
});

网格

如果你不喜欢每行有可变数量的方框,你可以制作一个网格。你会有一个容器,一排排,每一排都有你的盒子。

同样,你必须调整一些样式。

<Container style={styles.container}>
<Row style={styles.row}>
<Box />
<Box />
<Row />
<Row style={styles.row}>
<Box />
<Box />
<Row />
</Container>
const styles = StyleSheet.create({
container: {
width: "100%",
},
row: {
width: "100%",
justifyContent: 'space-between',
flexDirection: "row",
alignItems: "center",
},
item: {
width: 75,
height: 75,
marginRight: 10,
backgroundColor: "red",
},
});

最新更新