在React中将父项内的项目置于中心位置

时间:2016-07-08 05:04:29

标签: javascript html css reactjs styling

我无法在React中的另一个div中对齐两个组件。我正在使用父div(snippetButtonHolder)的相对定位和其子项的绝对定位(片段和按钮)。我希望片段在父节点中居中,按钮位于片段下方和右侧,但由于某些原因,当我使用这些属性时,它们相对于整个页面而不是父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>
        );
    }
}

1 个答案:

答案 0 :(得分:0)

尝试一下:

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',
    },
};