问题
I want to get the label on top of the input. But when I move it up in the code the CSS Focus styles stop working. On focus the label needs gets bigger. How to fix this? tried everything...
form {
margin-top: 25px;
}
input {
display:block;
}
form input:focus + label {
font-size: 1.5em;
}
<form>
<!-- DOESN'T WORK
=====================
-->
<label for="firstname">First name:</label>
<input id="firstname" name="firstname" type="text">
<br>
<!-- WORKS
=====================
-->
<input id="lasttname" name="firstname" type="text">
<label for="lasttname">Last name:</label>
</form>
回答1:
Try to wrap label and input in extra div, and use flex-box:
form {
margin-top: 25px;
}
form input:focus + label {
font-size: 1.5em;
}
.form-row {
display: flex;
flex-direction: column;
margin-bottom: 8px;
}
.form-row label {
order: 1;
}
.form-row input {
order: 2;
width: 141px;
}
<form>
<!-- DOESN'T WORK
=====================
-->
<div class='form-row'>
<input id="firstname" name="firstname" type="text">
<label for="firstname">First name:</label>
</div>
<!-- WORKS
=====================
-->
<input id="lasttname" name="firstname" type="text">
<label for="lasttname">Last name:</label>
</form>
回答2:
An jQuery solution.
$(function() {
$('form input[type="text"]').focus(function() {
$(this).prev('label').css("font-size", "1.5em");
});
$('form input[type="text"]').focusout(function() {
$(this).prev('label').css("font-size", "1em");
});
});
form {
margin-top: 25px;
}
form input:focus + label {
font-size: 1.5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<!-- DOESN'T WORK
=====================
-->
<label for="firstname">First name:</label>
<input id="firstname" name="firstname" type="text">
<!-- WORKS
=====================
-->
<input id="lasttname" name="firstname" type="text">
<label for="lasttname">Last name:</label>
</form>
来源:https://stackoverflow.com/questions/36400631/cant-get-label-and-input-to-work-on-focus