how to prevent child element from widening parent element's width in css

时间:2016-04-25 09:02:44

标签: html css

As you can see, I have a container, which is displayed as inline-block. Within this container, I have two divs, #line1 and #line2. They contain the same length of characters.

If I add more characters to #line1, the widths of #container and #line2 will increase accordingly. But that is not what I expect.

What I expect is that widths do not change and I can see characters, which I just add into #line1, through scrolling horizontally.

#container {
  display: inline-block;
}

#line1 {
  background: lightblue;
}

#line2 {
  background: orange;
}
<div id="container">
  <div id="line1">123</div>
  <div id="line2">123</div>
</div>

Update

Is there any method to achieve this effect if I do not want to use a fixed width? Simply because I want them to be responsive.

4 个答案:

答案 0 :(得分:1)

You can set fixed width on #line1 and add white-space: nowrap and overflow-x: auto

#container {
  display: inline-block;
}
#line1 {
  background: lightblue;
  width: 70px;
  white-space: nowrap;
  overflow-x: auto;
}
#line2 {
  background: orange;
}
<div id="container">
  <div id="line1">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Velit, a.</div>
  <div id="line2">123</div>
</div>

答案 1 :(得分:1)

If you don't want elements to fit the sizes of their contents, you should set their widths and heights. And overwflow: auto property takes care of the auto-appering scrolling for the non-fit content.

#container {
  display: inline-block;
  width: 50px;
}

#line1 {
  background: lightblue;
  width: 50px;
  height: 18px;
  word-wrap: break-word;
  overflow: auto;
}

#line2 {
  background: orange;
  width: 50px;
  height: 18px;
  word-wrap: break-word;
  overflow: auto;
}

https://jsfiddle.net/x8amz1f1/

答案 2 :(得分:1)

You first need a width or maximum-width on your line boxes width: 50px;.

The second thing is, you have to define an overflow so that the boxes gets scrollbars. With overflow: scroll; the scrollbars will always be visible, with overflow: auto; the scrollbars just appear when the content is exceeding the box.

Now your text will break after every word. You need white-space: nowrap; so that the text is not breaking in between.

    #container {
      display: inline-block;
    }

    #line1 {
      background: lightblue;
width: 50px;
overflow: scroll;
white-space: nowrap;
    }

    #line2 {
      background: orange;
width: 50px;
overflow: auto;
white-space: nowrap;
    }

<!-- language: lang-html -->

    <div id="container">
      <div id="line1">Lorem ipsum dolor sit amet, consetetur sadipscing elitr.</div>
      <div id="line2">Lorem ipsum dolor sit amet, consetetur sadipscing elitr.</div>
    </div>

Here is your example: https://jsfiddle.net/1Lkbttw0/

答案 3 :(得分:-1)

can make changes on line 2

#line2 {
    display: inline;
    background: orange;
}