CSS implements horizontal buttons without other techniques
P粉893457026
P粉893457026 2023-09-04 12:29:02
0
1
570
<p>I'm trying to create two horizontal buttons that are the same width - based on the width of the longest button. </p> <ul> <li>The text content of each button can be adjusted by the user on a separate page...so I have no control over their text length/the text length of the first button and the second button. </li> <li>I want the button to adjust to the length of the longest text, but not exceed the width of the page (like on mobile devices). </li> <li>I want the buttons to appear horizontally by default, but if they don't appear horizontally, stacked as columns. </li> <li>I need the button's text to wrap if the entire text won't fit. </li> </ul> <pre class="brush:php;toolbar:false;"><div class="button-container"> <div class="horizontal-button" data-role="yes">Yes</div> <div class="horizontal-button" data-role="no">No, sorry - I can't do that</div> </div></pre> <p>I tried various options...but can't get it to work! </p> <ul> <li>When using grid layout grid-template-colums: 1fr 1fr, I can't find a way to stack the buttons into columns when needed. </li> <li>I can't find a way to make the width of the button fit the length of the text when using flex and flex:1 1 0. </li> </ul> <p>Please help! </p> <p>Thank you very much! Damian. </p>
P粉893457026
P粉893457026

reply all(1)
P粉604848588

Let's try this option. What do you dislike about this approach?

div {
  background-color: rgba(0, 0, 0, 0.1);
}

.button-container {
  padding: 16px;
  display: flex;
  gap: 16px;
}

.horizontal-button {
  padding: 16px;
  flex: 1;
  text-align: center;
  word-wrap: hypens;
}

@media (max-width: 360px) {
  .button-container {
    flex-direction: column;
  }
}
<div class="button-container">
  <div class="horizontal-button" data-role="yes">Yes</div>
  <div class="horizontal-button" data-role="no">No, sorry - I cannot make it</div>
</div>

A: In this case the container/button takes up the entire width of the page... they don't adjust to the width of the text.

Q: Okay, then:

div {
  background-color: rgba(0, 0, 0, 0.1);
}

.button-container {
  margin: auto;
  padding: 16px;
  box-sizing: border-box;
  display: flex;
  align-items: stretch;
  gap: 16px;
  max-width: max-content;
}

.horizontal-button {
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 16px;
  flex: 1;
  text-align: center;
  max-width: 50%;
}

@media (max-width: 360px) {
  .button-container {
    flex-direction: column;
  }
  .horizontal-button {
    hyphens: auto;
    max-width: unset;
  }
}
<div class="button-container">
  <div class="horizontal-button" data-role="yes">Yes</div>
  <div class="horizontal-button" data-role="no">No, sorry - I cannot make it</div>
</div>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template