[英]How to align a div centered-below another while keeping them separate divs
[英]How to keep divs from breaking while keeping them centered
我有一個紅色的盒子和一個綠色的盒子,並排並居中。 當瀏覽器的寬度小於正方形的寬度時,它們會分成幾行。 如何將它們保持在一起?
(我嘗試使用組合寬度的容器div來完成將它們保持在一起的工作,但是它們不再居中。)
有什么建議么?
編碼:
<body>
<div style='text-align:center;font-size:0'>
<div style='display:inline-block;background-color:red;width:200px;height:50px'></div>
<div style='display:inline-block;background-color:green;width:200px;height:50px'></div>
</div>
</body>
您可以在此處運行它: https : //plnkr.co/edit/2De21ziNmaeleFmkPuPF?p=preview
這可以通過多種方式完成,這是3:
使用min-width
<div style='text-align:center;font-size:0; min-width: 400px'> <div style='display:inline-block;background-color:red;width:200px;height:50px'></div> <div style='display:inline-block;background-color:green;width:200px;height:50px'></div> </div>
使用white-space: nowrap
<div style='text-align:center;font-size:0; white-space: nowrap'> <div style='display:inline-block;background-color:red;width:200px;height:50px'></div> <div style='display:inline-block;background-color:green;width:200px;height:50px'></div> </div>
使用display: flex;
<div style='text-align:center;font-size:0;display: flex;justify-content: center'> <div style='display:inline-block;background-color:red;width:200px;height:50px'></div> <div style='display:inline-block;background-color:green;width:200px;height:50px'></div> </div>
嘗試使用Flex-box
.parent{ display:flex; border:1px solid green; width:500px; } .parent div{ background:green; width:100px; height:100px; margin:20px; }
<div class="parent"> <div>cell1</div> <div>cell2</div> </div>
希望這可以幫助
嘗試在框上使用width: 50%
,而不是width: 200px
。
如果為它們指定了固定寬度(例如200 + 200px),則在傳遞該div寬度(例如375px <divs總和的400px移動寬度)時,最后一個元素將滑到下一行。
彼此之間的寬度為35%,對於200像素,其外觀將完全與您想要的一樣。
<body>
<div style='text-align:center;font-size:0; width: 100%;'>
<div style='display:inline-block;background-color:red; width:35%;height:50px'></div>
<div style='display:inline-block;background-color:green; width:35%;height:50px'></div>
</div>
</body>
編輯:
這是一個有用的鏈接,用於更好地了解寬度選項取決於設備的寬度,我鼓勵您深入了解w3schools或其他可以更好地學習如何使用css和js操縱html元素的平台。 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.