width:当滚动条存在时,自动无法正确定位div

时间:2015-08-21 20:08:33

标签: html css

我有一个div,其中包含一些绝对定位且具有明确高度的内容。当内容超出高度时,会出现滚动条,但它不会尊重我的宽度:自动 - 滚动条会覆盖内容。

示例:

<style>    
    #main {
        height: 100px;
        border: 1px solid red;
        overflow-y: auto;
        position: absolute;
    }

</style>

<div id='main'>
    <div>test</div>
    <div>test</div>
    <div>testiiiiiiiing</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
</div>

这里发生了什么?这是浏览器错误吗?如何才能正确地遵循自动宽度?

2 个答案:

答案 0 :(得分:3)

您可以使用overflow-y: scroll;

<style>

 #main {
      height: 100px;
      border: 1px solid red;
      overflow-y: auto;
      position: absolute;
      padding-right: 10px;
    }
 #a {}

</style>

CodePen

答案 1 :(得分:2)

虽然您不太可能发现许多单词的宽度为100px,但我发现了两种可能性。

首先,只需添加一些padding-right即可为滚动条腾出空间。

&#13;
&#13;
    .main {
      height: 100px;
      border: 1px solid red;
      overflow-y: auto;
      position: absolute;
      padding-right: 25px;
    }
&#13;
<div class="main">
  <div class="a">Lorem ipsum.</div>
  <div class="a">Lorem ipsum dolor sit.</div>
  <div class="a">Lorem ipsum.</div>
  <div class="a">Loremipsumdolorsitametconsecteturametconsectetur.</div>
  <div class="a">Lorem</div>
  <div class="a">Lorem ipsum.</div>
  <div class="a">Lorem ipsum dolor sit.</div>
  <div class="a">Lorem ipsum.</div>
  <div class="a">Lorem ipsum dolor sit amet, consectetur.</div>
  <div class="a">Lorem</div>
</div>
&#13;
&#13;
&#13;

其次,如果使用word-wrap: break-word;

到达那个边缘,强制所有单词中断

&#13;
&#13;
.main {
      height: 100px;
      border: 1px solid red;
      overflow-y: auto;
      position: absolute;
      padding-right: 25px;
    }
    .main.breaking {
      padding-right: none;
      word-wrap: break-word;
    }
&#13;
<div class="main breaking">
  <div class="a">Lorem ipsum.</div>
  <div class="a">Lorem ipsum dolor sit.</div>
  <div class="a">Lorem ipsum.</div>
  <div class="a">Loremipsumdolorsitametconsecteturametconsectet</div>
  <div class="a">Lorem</div>
  <div class="a">Lorem ipsum.</div>
  <div class="a">Lorem ipsum dolor sit.</div>
  <div class="a">Lorem ipsum.</div>
  <div class="a">Lorem ipsum dolor sit amet, consectetur.</div>
  <div class="a">Lorem</div>
</div>
&#13;
&#13;
&#13;