乐闻世界logo
搜索文章和话题

How to reduce spacing between antd Form.Items?

1个答案

1

When using Ant Design (abbreviated as antd) form components, we can adjust the spacing between form items in multiple ways. Below, I will share some common methods:

1. Using CSS Styles Adjustment

The most straightforward way is to adjust the styles of Form.Item components using CSS. For example, we can reduce the margin or padding to decrease the spacing between form items.

Example Code:

css
// Custom CSS class .my-form-item { margin-bottom: 8px; // Default might be 16px } // Using this style <Form.Item className="my-form-item"> <Input placeholder="Please enter content" /> </Form.Item>

2. Using Row and Col Layout Control

Use the Row and Col components to control the layout of form items. Adjust the gutter property to control the spacing between columns.

Example Code:

jsx
<Row gutter={16}> // Adjust to a smaller value to reduce spacing <Col span={12}> <Form.Item> <Input placeholder="Please enter content" /> </Form.Item> </Col> <Col span={12}> <Form.Item> <Input placeholder="Please enter content" /> </Form.Item> </Col> </Row>

3. Global Configuration or Theme Modification

For large projects, if you need to uniformly adjust the spacing between form items across the project, consider modifying Ant Design's theme variables.

Ant Design supports global style adjustments by configuring Less variables. For example, adjust the @form-item-margin-bottom variable to modify the default margin of Form.Item.

Example Configuration:

less
@import "~antd/dist/antd.less"; @form-item-margin-bottom: 8px; // Reduce the default spacing

4. Form's layout Property

The Form component in Ant Design supports the layout property, which can be horizontal or vertical. For vertical layout (vertical), the default spacing is typically smaller than for horizontal layout (horizontal), so consider choosing the appropriate layout based on your needs.

Example Code:

jsx
<Form layout="vertical"> <Form.Item> <Input placeholder="Please enter content" /> </Form.Item> <Form.Item> <Input placeholder="Please enter content" /> </Form.Item> </Form>

By using the above methods, we can effectively adjust the spacing between Ant Design form items, making the interface more compact and aesthetically pleasing. Specifically, which method to choose depends on the specific requirements of the project and the existing codebase.

2024年8月9日 20:48 回复

你的答案