Skip to content

1. 部分元素居右

  • flex方案

仅需给父元素设置flex布局,给要居右的子元素们的第一个子元素设置 margin-left:auto;即可

css
.father {
    display:flex;
}

.rightDiv {
    margin-left:auto;
}
.father {
    display:flex;
}

.rightDiv {
    margin-left:auto;
}

2. 让子元素自动占满一行

可以使用Flex布局中的flex-wrap: wrapflex-basis属性来实现。具体实现方法如下:

css
.parent {
display: flex;
flex-wrap: wrap;
}

.parent div {
flex-basis: calc(100% / 3); 
/* 使用`flex-basis`将每个子元素的初始宽度设置为父元素宽度除以3,即每行分成3份。 */
}
.parent {
display: flex;
flex-wrap: wrap;
}

.parent div {
flex-basis: calc(100% / 3); 
/* 使用`flex-basis`将每个子元素的初始宽度设置为父元素宽度除以3,即每行分成3份。 */
}

3. 固定宽度的子元素均匀分布

可以使用Flex布局中的justify-content: space-between属性来实现。具体实现方法如下:

css
.parent {
display: flex;
justify-content: space-between;
}

.parent div {
width: 200px; /* 固定宽度 */
}
.parent {
display: flex;
justify-content: space-between;
}

.parent div {
width: 200px; /* 固定宽度 */
}

4. 子元素紧贴父元素并均匀分布

父元素有一行子元素,子元素直接有margin,子元素与父元素无margin或者padding。

css
.father {
    display:flex;
}

.father > div {
    margin-right:20px;
}
/* 单独给最后一个子元素设置 */
.lastItem { 
    margin-right:0;
}
.father {
    display:flex;
}

.father > div {
    margin-right:20px;
}
/* 单独给最后一个子元素设置 */
.lastItem { 
    margin-right:0;
}
css
.father {
    display:flex;
    /* 让父元素内右边距变为负数 */
    padding-right:-20px;
}

.father > div {
    margin-right:20px;
}
.father {
    display:flex;
    /* 让父元素内右边距变为负数 */
    padding-right:-20px;
}

.father > div {
    margin-right:20px;
}