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
783 views
in Technique[技术] by (71.8m points)

google chrome - CSS Grid - unnecessary word break

I have a problem with CSS grid.

In the following snippet extracted from the codebase, I have a very simple HTML structure with grid layout. Content is set to break-word to prevent text from overflowing. Event though there is enough space for the text to NOT get broken, it does create a line break just before the last letter.

My understanding was that in grid layout, by default, items are calculated to fit the content as much as possible, which is somehow not the case in this example.

Removing padding from content or margins from grid item does solve the issue, but margin is there for centering and padding is also needed.

Is there any property I have to or can use to solve this problem?

P.S. To my knowledge, the bug is not present in Firefox, I have found it in Chrome and Safari so far.

.grid {
  display: grid;
  grid-template-columns: auto;
}

.item {
  margin: 0 auto;
}

p {
  word-break: break-word;
  padding: 0 4%;
}
<div class="grid">
  <div class="item">
    <p>HOTEL</p>
    <p>GRAND</p>
  </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)

It's not a bug but a complex calculation.

There is a kind of cycle to calculate the final width of the element which create the issue. The width is first calculated considering the content (a shrink-to-fit behavior based on the properties you used) then using percentage value with padding will consider the calculated width1. At the end, we will reduce the calculated padding from the width creating the word break.

This will happen with the smallest value since in all the cases the width will always be less than the needed width to contain the longest word:

.grid {
  display: grid;
  grid-template-columns: auto;
}
.item {
  margin:auto;
  border:1px solid;
}
.pad p {
  word-break: break-word;
  padding: 0 1%;
}
<div class="grid">
  <div class="item">
    <p>HOTEL</p>
    <p>I_WILL_FOR_SURE_BREAK</p>
  </div>
</div>

<div class="grid">
  <div class="item pad">
    <p>HOTEL</p>
    <p>I_WILL_FOR_SURE_BREAK</p>
  </div>
</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

...