I'm trying to input
get one to stay centered like this:
My understanding is that to center an element in block I should use margin-left:auto
and margin-right:auto
yet I don't get the effect I want.
This is my code:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.1.1/material.indigo-pink.min.css">
<style media="screen">
.input-placa {
margin-right: auto;
margin-left: auto;
}
</style>
</head>
<body>
<div class="mdl-grid">
<div class="mdl-cell mdl-cell--4-col"></div>
<div class="mdl-cell mdl-cell--4-col">
<div class="mdl-textfield mdl-js-textfield input-placa">
<input class="mdl-textfield__input">
<label class="mdl-textfield__label" for="placa">Placa</label>
</div>
</div>
<div class="mdl-cell mdl-cell--4-col"></div>
</div>
<script defer src="https://code.getmdl.io/1.1.1/material.min.js"></script>
</body>
</html>
You don't get the desired effect because the class
.mdl-textfield
makes thediv
have adisplay:inline-block
and so the method doesn't work because it's not a block (withdisplay:block
).The solution is simple: modify the style you already have in
.input-placa
so that it is also considered ablock
(it would also work with valueinherit
):If you look now, it does center the field well at full screen on a computer, but it fails when the size is tablet or phone (as in the case of the window below):
This happens because in
grid
the columns are defined for large screen (mdl-cell--N-col
), but have no definition for smaller screens (mdl-cell--N-col-tablet
andmdl-cell--N-col-phone
).So it's not just about centering the element in the cell, but you also have to make the cells fit in a row (and since it's centered in the middle cell, it will stay centered).