簡體   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