在 React 中将项目居中在父项中时出现问题

Trouble centering items within parents in React

本文关键字:问题 React 项目      更新时间:2023-09-26

我在 React 中对齐另一个div 中的两个组件时遇到问题。我正在为父div(片段按钮持有人)使用相对定位,为其子级(片段和按钮)使用绝对定位。我希望代码段在父级中居中,按钮位于代码段下方和右侧,但由于某种原因,当我使用这些属性时,它们相对于整个页面而不是父div 定位。有没有人对我应该做些什么不同的事情提出建议?

const styles = {
    module: {
        marginTop: '30px',
        padding: '20px',
    },
    snippet: {
        backgroundColor: '#f2f2f2',
        border: 'solid 1px #ccc',
        borderRadius: '4px',
        margin: '0 auto',
        padding: '10px',
        width: '100%',
        position: 'absolute',
        left: '50%',
    },
    snippetButtonHolder: {
        width: '95%',
        position: 'relative',
    },
    button: {
        float: 'right',
        marginTop: '5px',
        position: 'absolute',
        left: '94%',
    },
};
export default class CodeSnippet extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div style={styles.module}>
                <div style={styles.snippetButtonHolder}>
                    <div style={styles.snippet}>
                        <div 
                            {'text will go here'}
                        </div>
                        {this.state.showButton ?
                            <button
                                style={styles.button}>
                                Press me
                            </button>
                        : null}
                    </div>
                </div>
            </div>
        );
    }
}

试一试:

const styles = {
    module: {
        marginTop: '30px',
        padding: '20px',
    },
    snippet: {
        backgroundColor: '#f2f2f2',
        border: 'solid 1px #ccc',
        borderRadius: '4px',
        display: 'inline-block',
        overflow: 'hidden',
        padding: '10px',
    },
    snippetButtonHolder: {
        textAlign: 'center',
        width: '95%',
    },
    button: {
        float: 'right',
        marginTop: '5px',
    },
};