当浏览器重新调整大小时,如何防止包含变量宽度的div元素?

时间:2018-04-15 15:53:26

标签: html css

我在这里找到类似的答案,使用固定宽度解决问题,例如" How can I prevent floated div elements from wrapping when the browser is re-sized?"。

在我的情况下,我有第一个div是一个72px固定宽度的正方形的徽标。第二个div是可变宽度,在div内部包含一个h1和h2元素。无论第二个div是一个块还是内联块,当浏览器调整大小时,第二个div都会在徽标下面包裹起来。

我想要的是第二个div保持在第一个div的右边,但是当浏览器调整到较小的宽度时,h1和h2会在内部换行。

例如,当浏览器完全最大化时,div看起来像这样:

|div 1| |div 2                |
|logo | |h1                /h1|
|fixed| |h2                /h2|

但是当浏览器重新调整大小时会发生这种情况:

|div 1| 
|logo | 
|fixed| 
|div 2                |
|h1                /h1|
|h2                /h2|

如何让div 2保持在右侧div 1的旁边,但是像这样进行h1h2换行:

|div 1| |div 2        |
|logo | |h1           |
|fixed| |          /h1|
        |h2           |  
        |          /h2|

Div 2没有固定宽度,也不能指定宽度百分比,因为div 1和div 2都需要与浏览器一样宽,div 1是固定宽度。这是我目前的设置:



.title-area {
  float: left;
  overflow: hidden;
  padding: 0;
  width: 100%;
}

.wrap-logo {
  float: left;
  padding: 0;
  width: 72px;
  display: block;
}

.wrap-title {
  float: left;
  padding: 0;
  width: 100%;
  display: block;
}

.site-logo {
  float: left;
  max-width: 72px;
  display: block;
  vertical-align: top;
}

.title-wrap {
  display: block;
}

.subtitle-wrap {
  display: block;
}

h1.site-description,
h2.site-title {
  text-align: left;
  font-weight: bold;
  float: left;
  display: inline-block;
}

h1.site-title {
  font-size: 1.8em;
  padding: 0;
  text-transform: uppercase;
}

h2.site-description {
  font-size: 1.2em;
  padding: 0;
}

<div class="title-area">
  <div class="wrap-logo">
    <img class="site-logo" src="/seal.svg" alt="Logo">
  </div>
  <div class="wrap-title">
    <div class="title-wrap">
      <h1 class="site-title">Reasonably Long Title Label Description Within Div 2</h1>
    </div>
    <div class="subtitle-wrap">
      <h2 class="site-description">Even longer subtitle label description that should wrap on resize</h2>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

使用float停止。

他们在那里,但不要滥用他们。他们打破了页面的流动,发生了疯狂。

发生这种情况的原因是因为页面的流程被破坏了,所以浏览器不知道如何处理第二个div的宽度,他简单地应用它是100%宽度。

据我所知,您正在寻找display: inline-block,但如果您希望自己的生活更轻松,请flex

我想我知道你想做什么。这就是我要做的事情:

.main-container {
  width: 100%;
  display: flex
}

.main-container .right-container {
  width: 12%;
}

.main-container .left-container {
  display:flex;
  flex-direction: column;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <div class="main-container">
    <div class="right-container">
      <div>something here</div>
      <div>logo here</div>
      <div>fixed</div>
    </div>
    <div class="left-container">
      <h1>Some huge string just appeared in the galaxy and this will be the key</h1>
      <h2>Some huge string just appeared in the galaxy and this will be the key</h2>
    </div>
  </div>
</body>
</html>

这是吗?

希望有所帮助:)

相关问题