Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
558 views
in Technique[技术] by (71.8m points)

html - How do browsers calculate width when child depends on parent, and parent's depends on child's

I'm experiencing various glitches, weird rendering artifacts and so forth on my React application and was wondering about the way defining dimensions works from a browser's point of view.

Let's say I have a grid display, and there's a div which has grid-template-columns: 1fr auto 1fr and a child div which has spans grid-column: 2 / 3 - in other words spanning in the auto area of the parent grid.

As I understand, the value auto in grid template columns defines the column to be sized to fit its contents.

Now let's add an img with the max-width set to 100% - in other words, we don't want to exceed the size of the parent container.

However, the parent container's width is determined by the auto rule - so how can the browser let the child know to take up 100%?

Example

.box {
  display: grid;
  grid-template-columns: 1fr auto 1fr;
  background-color: lightblue;
}

.box>div {
  border: 1px solid red;
  grid-column: 2 / 3;
  margin: 10px 10px 0px;
}
<div class="box">
  <div style="">
    <img src="https://via.placeholder.com/800" style="max-width:100%">
  </div>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To explain this, I will start with a more simplified example that will produce the same output:

<div style="display:inline-block">
  <img src="https://via.placeholder.com/1000x100">
</div>

<div style="display:inline-block">
  <img src="https://via.placeholder.com/1000x100" style="max-width:100%">
</div>

<div style="display:inline-block">
  <!-- even a big explicit width specified won't change the behavior -->
  <img src="https://via.placeholder.com/1000x100" style="wdith:2000px;max-width:100%">
</div>

<div style="display:inline-block">
  <img src="https://via.placeholder.com/1000x100" style="width:100%">
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...