#css# flex布局小技巧之让某个子元素靠右或靠左显示

以下以块元素的Flex布局为示例:
只需要两句代码,轻松搞定!

代码1:
父元素里面加入以下代码:
(父盒子加了display: flex,就相当于起到浮动的效果,盒子会自行排列成一排)

display: flex

代码2:
在需要移动的子元素里(此处为靠右显示),加入以下代码:

margin-left: auto

**子元素居右显示
示例如下:

【 html版块示例 】

 
<!--我是父盒子-->
<div class="father_box">
<!--三个子盒子-->
  <div class="son_box1">普通盒子甲</div>
  <div class="son_box2">普通盒子乙</div>
  <div class="son_box3">靠右显示盒子</div>
</div>

【 css版块示例】


  .father_box {
     margin: 100px auto;
     width: 300px;
     height: 200px;
     background-color: rebeccapurple;
     display: flex; 
   }
   .son_box1 {
     width: 80px;
     height: 80px;
     background-color: cornflowerblue;
   }
    .son_box2 {
     width: 80px;
     height: 80px;
     background-color: pink;
   }
   .son_box3 {
     width: 100px;
     height: 100px;
     background-color: blue;
     color: #ff9d00;
     margin-left: auto;
   }
   

网页显示效果:
在这里插入图片描述

子元素居左显示
示例如下:

【 html版块示例 】

 
<!--我是父盒子-->
<div class="father_box">
<!--三个子盒子-->
  <div class="son_box1">靠左显示盒子</div>
  <div class="son_box2">盒子甲</div>
  <div class="son_box3">盒子乙</div>
</div>

【 css版块示例】


  .father_box {
    margin: 100px auto;
     width: 300px;
     height: 200px;
     background-color: rebeccapurple;
     display: flex; 
   
   .son_box1 {
     width: 100px;
     height: 100px;
     background-color: mediumspringgreen;
     margin-right: auto;
   }
    .son_box2 {
     width: 80px;
     height: 80px;
     background-color: saddlebrown;
   }
   .son_box3 {
     width: 80px;
     height: 80px;
     background-color: blue;
     color: #ff9d00;
   }
   

网页显示效果:
在这里插入图片描述

小结:

  • 父盒子加了display: flex,就相当于起到浮动的效果,盒子会自行排列成一排;

  • 若想让父盒子里的某一个盒子靠右显示,其他盒子居左, 只需要在父盒子里面,
    加入display: flex,在想要移动的盒子里面,加入margin-left: auto即可;

  • 同理,如果你想让第一个盒子向左显示,其余盒子都向右显示,只需要给左边的第一个盒子设置 margin-right:auto即可;

  • 此外,行内元素也可以使用Flex布局,子元素的代码如下:

.box{ display:inline-flex;}

以上,完毕。

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐