Html和reactNative Flex布局实现一行4个平均分

2023-11-24  本文已影响0人  王宣成

html

<style>
    .card_wrap {
        margin-left: 10px;
        margin-right: 10px;
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;
    }

    .c_item {
        flex: 1;
        height: 120px;
        margin: 0 5px 5px 0;
        background-color: red;
        width: calc((100% - 15px) / 4);
        min-width: calc((100% - 15px) / 4);
        max-width: calc((100% - 15px) / 4);

        &:nth-child(4n) {
            margin-right: 0;
        }
    }
</style>
<div class="card_wrap">
    <div class="c_item"></div>
    <div class="c_item"></div>
    <div class="c_item"></div>
    <div class="c_item"></div>
    <div class="c_item"></div>
    <div class="c_item"></div>
    <div class="c_item"></div>
    <div class="c_item"></div>
    <div class="c_item"></div>
    <div class="c_item"></div>
</div>

react native

import React from 'react';
import { View, StyleSheet, Dimensions } from 'react-native';

const screenWidth = Dimensions.get('window').width;
const itemMargin = 5; // margin between items
const itemWidth = (screenWidth - itemMargin * 5) / 4; // 5 margins for 4 items in a row

const App = () => {
  return (
    <View style={styles.cardWrap}>
      <View style={styles.cItem} />
      <View style={styles.cItem} />
      <View style={styles.cItem} />
      <View style={styles.cItem} />
      <View style={styles.cItem} />
      <View style={styles.cItem} />
      <View style={styles.cItem} />
      <View style={styles.cItem} />
      <View style={styles.cItem} />
      <View style={styles.cItem} />
    </View>
  );
};

const styles = StyleSheet.create({
  cardWrap: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'flex-start',
    marginHorizontal: itemMargin / 2,
  },
  cItem: {
    flexGrow: 0,
    height: 120,
    margin: itemMargin / 2,
    backgroundColor: '#999',
    width: itemWidth,
  },
});

export default App;
上一篇下一篇

猜你喜欢

热点阅读