Is it possible to center text in select box?

后端 未结 19 2399
一整个雨季
一整个雨季 2020-11-22 11:21

I tried this: http://jsfiddle.net/ilyaD/KGcC3/

HTML:


                        
    
提交评论

  • 2020-11-22 11:46

    You have to put the CSS rule into the select class.

    Use CSS text-indent

    Example

    <select class="day"> /* option 1 option 2 option 3 option 4 option 5 here */ </select>
    

    CSS code

    select { text-indent: 5px; }
    
    0 讨论(0)
  • 2020-11-22 11:49

    Alternative "fake" solution if you have a list with options similar in text length (page select for example):

    padding-left: calc(50% - 1em);
    

    This works in Chrome, Firefox and Edge. The trick is here to push the text from the left to the center, then substract the half of length in px, em or whatever of the option text.

    Best solution IMO (in 2017) is still replacing the select via JS and build your own fake select-box with divs or whatever and bind click events on it for cross-browser support.

    0 讨论(0)
  • 2020-11-22 11:50

    Not quite Centering but using example above you can make a left margin in select box.

    <style>.UName { text-indent: 5px; }</style><br>
    
    <select  name="UserName" id="UserName" size="1">
        <option class="UName" selected value="select">Select User</option>
        <option class="UName" value="User1">User 1 Name</option>
        <option class="UName" value="User2">User 2 Name </option>
        <option class="UName" value="User3">User 3 Name</option>
    </select>
    
    0 讨论(0)
  • 2020-11-22 11:50

    While you cannot center the option text within a select, you can lay an absolutely positioned div over the top of the select to the same effect:

    #centered
    {
      position: absolute;
      top: 10px;
      left: 10px;
      width: 818px;
      height: 37px;
      text-align: center;
      font: bold 24pt calibri;
      background-color: white;
      z-index: 100;
    }
    
    #selectToCenter
    {
      position: absolute;
      top: 10px;
      left: 10px;
      width: 840px;
      height: 40px;
      font: bold 24pt calibri;
    }
    
    $('#selectToCenter').on('change', function () {
        $('#centered').text($(this).find('option:selected').text());
    });
    
    <select id="selectToCenter"></select>
    <div id="centered"></div>
    

    Make sure the both the div and select have fixed positions in the document.

    0 讨论(0)
  • 2020-11-22 11:53

    just using this:

    select {
    
    text-align-last: center;
    padding-right: 29px;
    
    }
    
    0 讨论(0)
  • 提交回复
    热议问题