Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...