Centered form with material design lite

Clarkie picture Clarkie · Jul 16, 2015 · Viewed 58.8k times · Source

I am looking for an easy to get a login form centered on the screen using Google's Material Design Lite library.

I've been through a number of iterations and this is the best I've come up with:

<div class="mdl-cell--12-col mdl-grid">
    <div class="mdl-cell mdl-cell--4-col mdl-cell--2-col-tablet">&nbsp;</div>

    <div class="mdl-grid mdl-cell--4-col">

        <div class="mdl-textfield mdl-js-textfield mdl-cell-12-col">
            <input class="mdl-textfield__input" type="text" id="username" />
            <label class="mdl-textfield__label" for="username">Username</label>
        </div>

        <div class="mdl-textfield mdl-js-textfield mdl-cell-12-col">
            <input class="mdl-textfield__input" type="password" id="password" />
            <label class="mdl-textfield__label" for="password">Password</label>
        </div>
    </div>

    <div class="mdl-cell mdl-cell--4-col mdl-cell--2-col-tablet">&nbsp;</div>
</div>

Is there a better way of achieving a centered form on all screen sizes?

The divs with &nbsp; feel really yucky!

Answer

passerby picture passerby · Aug 21, 2015

How about using "mdl-layout-spacer": See codepen

<div class="mdl-grid">
    <div class="mdl-layout-spacer"></div>
    <div class="mdl-cell mdl-cell--4-col">This div is centered</div>
    <div class="mdl-layout-spacer"></div>
</div>

Or if you prefer a css solution: Add an extra class to the grid containing the column to be centered. See codepen

<div class="mdl-grid center-items">
    <div class="mdl-cell mdl-cell--4-col">This div is centered</div>
</div>

.mdl-grid.center-items {
  justify-content: center;
}

Both options play nice when resizing.