搜尋

首頁  >  問答  >  主體

CSS實現水平按鈕,無需其他技術

<p>我正在嘗試創建兩個水平按鈕,它們的寬度相同 - 基於最長按鈕的寬度。 </p> <ul> <li>每個按鈕的文字內容可以由使用者在單獨的頁面上調整...因此我無法控制他們的文字長度/第一個按鈕和第二個按鈕的文字長度。 </li> <li>我希望按鈕能夠根據最長文字的長度進行調整,但不要超出頁面的寬度(例如在行動裝置上)。 </li> <li>我希望按鈕預設水平顯示,但如果它們不能水平顯示,則堆疊為列。 </li> <li>如果整個文字無法適應,我需要按鈕的文字換行。 </li> </ul> <pre class="brush:php;toolbar:false;"><div class="button-container"> <div class="horizo​​ntal-button" data-role="yes">是</div> <div class="horizo​​ntal-button" data-role="no">不,抱歉 - 我不能做到</div> </div></pre> <p>我嘗試了多種選項...但無法使其正常工作! </p> <ul> <li>當使用網格佈局grid-template-colums: 1fr 1fr時,我找不到一種方法來在需要時將按鈕堆疊為列。 </li> <li>當使用flex和flex:1 1 0時,我找不到一種方法來使按鈕的寬度適應文字的長度。 </li> </ul> <p>請幫忙! </p> <p>非常感謝! 達米安。 </p>
P粉893457026P粉893457026527 天前612

全部回覆(1)我來回復

  • P粉604848588

    P粉6048485882023-09-05 00:33:10

    讓我們嘗試這個選項。您對這種方法有什麼不喜歡的地方?

    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: 在這種情況下,容器/按鈕佔據了整個頁面的寬度...它們不會根據文字的寬度進行調整。

    Q: 好的,那麼:

    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>

    回覆
    0
  • 取消回覆