繁体   English   中英

如何在没有绝对位置和浮动的情况下将div定位到容器的右端?

[英]How to position a div to right end of the container without absolute position and float?

有没有可能在不使用绝对位置和浮动的情况下将div定位到容器的右侧? 每当我使用float:rightposition: absolute ,容器都不知道浮动或定位的元素内容高度,这会导致布局问题。

我尝试将固定高度设置为浮动或定位的元素,然后将padding-bottom添加到浮动或定位的元素的高度。

.container{
  padding-bottom: 20px;
}

.container .float_right{
   float: right;
   height: 20px;
}

即使可以,但我正在寻找比这更好的解决方案。 有人可以告诉我是否有其他解决方法?

只需添加overflow: hidden; .container在这里阅读更多

.container{
  padding-bottom: 20px;
  overflow: hidden;
}

.container .float_right{
   float: right;
   height: 20px; /* no longer necessary */
}

为了让您看到overflow: hidden;的效果,我一直在设置padding-topheight样式overflow: hidden; 不需要固定的高度。

码笔

.container样式设置.container text-align:right给parent

   .container{
      padding-bottom: 20px; 
      text-align:right;
      width:100%
    }

.container .float_right{
       //float: right;
       height: 20px;
       display:inline-block;
    }

 .container{ padding-bottom: 20px; text-align:right; width:100% } .container .float_right{ height: 20px; display:inline-block; } 
 <div class="container"> <div class="float_right"> Right align div </div> </div> 

或将父级设置为display:flexmargin-left: auto; 给孩子div

 .container{ padding-bottom: 20px; width:100%; display:flex; } .container .float_right{ height: 20px; margin-left: auto; } 
 <div class="container"> <div class="float_right"> Right align div </div> </div> 

或固定容器的高度,您可以添加具有类清除和设置样式的div

.clear{
      clear:both;
  }

 .container{ padding-bottom: 20px; background:red; width:100% } .container .float_right{ float: right; height: 40px; } .clear{ clear:both; } 
 <div class="container"> <div class="float_right"> float right </div> <div class="clear"></div> </div> 

即使我接受了答案,但我认为以下解决方案比所有其他解决方案要好一些,因为它不需要您在容器或浮动元素的高度上使用padding-bottom。

.container:after{
      content: "";
      display: table;
      clear: both;
}

将以上代码应用于容器元素; 这将解决问题。

归功于 https://css-tricks.com/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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