meds
meds

Reputation: 22956

CSS translate position to center of screen?

I have the following css (defined in react material-ui withStyles method):

const styles = (theme: Theme) => {
    return ({
        display: {
            transition: theme.transitions.create('transform')
        },
        displayHighlight: {
            transform: 'translateX(50%)',
            position: 'fixed',
            top: 0,
            zIndex: 10,
            transition: theme.transitions.create('transform')
        }
    }) as any;
}

The CSS is applied to cards which are displayed in a masonry grid in react virtualized, this is what the card render function does:

return <div className={this.state.expanded ? this.props.classes.displayHighlight : this.props.classes.display}>
    <Card style={{ width: this.props.columnWidth }}>
        <PreviewRenderer columnWidth={this.props.columnWidth}
            embedVideo={this.props.submission.embedVideo}
            imagePreview={this.props.submission.preview} />
        <CardHeader
            style={{ textAlign: 'left' }}
            title={this.props.submission.title}
        />

        <CardContent>
            <div style={{ width: '40px', float: 'right' }}>
                {this.props.submission.id && <RatingBar submissionId={this.props.submission.id.toString()} />}
            </div>

            <Button onClick={() => this.setState({ expanded: !this.state.expanded })}>Expand</Button>
        </CardContent>
    </Card>
</div>

When someone clicks on 'expand' I'd like to scale up the card and move it to the center of the browser window.

Is that at all possible in css or by passing in the screen dimensions to the defined css to make it move where I want?

Upvotes: 0

Views: 7692

Answers (1)

Gerard Reches
Gerard Reches

Reputation: 3154

Yes, it is possible to center an element in the page with CSS (in the page, which is not the same as the entire browser window).

I'm not into Reactjs, but you can try changing your code this way:

const styles = (theme: Theme) => {
    return ({
        display: {
            transition: theme.transitions.create('transform')
        },
        displayHighlight: {
            transform: 'translate(-50%,-50%)',
            position: 'fixed',
            top: 50%,
            left: 50%,
            zIndex: 10,
            transition: theme.transitions.create('transform')
        }
    }) as any;
}

You can center an element in the page with the following CSS properties:

position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);

What this does is center the top-left corner of your container in the center of the screen, and then use transform: translate(-50%,-50%) to move the center of the element to where its top-left corner was before: in the center of the page.

The difficult part would be to achieve a smooth transition from its initial position: relative to position: fixed.

Upvotes: 4

Related Questions