【问题标题】:How to keep divs from breaking while keeping them centered如何让 div 在保持居中的同时不被破坏
【发布时间】:2016-10-24 20:52:52
【问题描述】:

我有一个红色的盒子和一个绿色的盒子,并排且居中。当浏览器宽度小于正方形的宽度时,它们会分成单独的行。如何将它们保持在一起?

(我尝试使用具有组合宽度的容器 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

【问题讨论】:

  • min-width:400px; margin: 0 auto; 添加到您的外部 div...
  • @War10ck 要使margin: 0 auto 工作,您需要一个小于视口(或其父级)的宽度,在这种情况下,这将永远不会发生......对于min-width,答案已经是给定的,所以也许更好地支持这样的答案而不是用评论回答

标签: html css


【解决方案1】:

这可以通过多种方式完成,这里有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>

【讨论】:

    【解决方案2】:

    尝试使用 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>

    希望对你有帮助

    【讨论】:

      【解决方案3】:

      如果你给它们一个固定的宽度(例如 200+200px),当该 div 宽度被传递时(例如移动宽度为 375px

      彼此之间的宽度为 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>
      

      Here is the link to your code

      编辑:

      这是一个有用的链接,可以更好地理解宽度选项取决于设备的宽度,我鼓励您深入了解 w3schools 或其他平台,在这些平台上您可以更好地学习如何操作 html 元素,使用css和js。

      screen-width

      【讨论】:

        【解决方案4】:

        尝试在盒子上使用width: 50% 而不是width: 200px

        【讨论】:

          猜你喜欢
          • 2011-06-27
          • 1970-01-01
          • 1970-01-01
          • 2023-03-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-23
          • 2014-04-17
          相关资源
          最近更新 更多