简体   繁体   中英

With media query how do I make a form that uses grid layout to layout labels and form elements when the screen is greater than or equal to 600px wide?

Is my code correct? I'm a bit confused because I'm not entirely sure if just listing the form class means that the labels and elements in the form will be adjusted to a grid layout also.

@media only screen and (min-width: 600px) {
.form {
display:grid}
}

You code here would give any element that has a class of 'form' the display property of grid at screens 600px wide and above. But what will happen to the form elements themselves would depend on the actual html markup contained in you form. In your example all DIRECT decedents of the element with the form class will become grid items, but that doesn't automatically carry down to those item's decedents also.

Let say you have 6 text fields, each has a label. You would want to wrap each label and field pair inside a div and place these as the direct children of your .form. You would then have 6 divs inside the form to set you grid layout, and each grid-item will contain all actual form markup needed for that field.

In this example you should see 6 grid-items in 3 columns.

*You don't need the 2nd or 3rd CSS declarations, these are just to make this example a bit more pretty.

 @media only screen and (min-width: 600px) { .form { display: grid; grid-gap: 20px; grid-template-columns: 2fr 2fr 2fr; } .form > div { border: 1px solid #ccc; padding: 10px; } .form > div > * { display: block; } }
 <form class="form"> <div> <label>Field name</label> <input type="text" /> </div> <div> <label>Field name</label> <input type="text" /> </div> <div> <label>Field name</label> <input type="text" /> </div> <div> <label>Field name</label> <input type="text" /> </div> <div> <label>Field name</label> <input type="text" /> </div> <div> <label>Field name</label> <input type="text" /> </div> </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM