How can I align the text in a dropdown menu to the center on Safari?

How can I center the option text in a drop down menu using CSS?

display: block;
height: 60px;
margin-left: 10%;
margin-right: 10%;
margin-top: 10px;
min-height: 60px;
text-align: center;

The option text is centered in Firefox browser, but not in Safari. Is there a solution to get the text aligned in the center in Safari browser?

Answer №1

To enhance the spacing and eliminate the need for height, consider making these adjustments in your code:

display: block;
margin-left: 15%;
margin-right: 15%;
margin-top: 15px;
padding-top: 15px;
padding-right: 25px;
padding-bottom: 15px;
padding-left: 25px;

UPDATE

If padding causes issues in Safari (iPhone), consider using text-indent as an alternative. Ensure that the text indent matches the width of your dropdown menu. Here's an updated version of your code:

display: block;
height: 80px;
margin-left: 15%;
margin-right: 15%;
margin-top: 15px;
min-height: 80px;
width: 260px; /* 240px width plus 20px for text-indent */
text-indent: 20px;

Answer №2

To center the text vertically, consider utilizing top and bottom padding and eliminating height.

padding: 30px;

Answer №3

If you're in a bind, check out this crossbrowser select code snippet on CodePen.

$(document).ready(() => {
    $('.crossbrowser-select').on('click', crossbrowserSelectOnClickEvent);
    $('.crossbrowser-select').on('mouseWheelDown', crossbrowserSelectOnMouseWheelDownEvent);
    $('.crossbrowser-select').on('mouseWheelUp', crossbrowserSelectOnMouseWheelUpEvent());
    $('.crossbrowser-select > .option').on('click', crossbrowserSelectItemOnClickEvent);
    $('.crossbrowser-select').focusout('click', crossbrowserSelectOnFocusOutEvent);

    //Firefox
    $('.crossbrowser-select').bind('DOMMouseScroll', function(e){
        if (e.originalEvent.detail > 0) {
            //scroll down
            chooseNextItem($(this));
        } else {
            //scroll up
            choosePreviousItem($(this));
        }
        //prevent page fom scrolling
        return false;
    });
    //IE, Opera, Safari
    $('.crossbrowser-select').bind('mousewheel', function(e){
        if(e.originalEvent.wheelDelta < 0) {
            //scroll down
            chooseNextItem($(this));
        }else {
            //scroll up
            choosePreviousItem($(this));
        }

        //prevent page fom scrolling
        return false;
    });

    $('.crossbrowser-select').keyup(function(event) {
        if (event.keyCode === 32) { //Enter
            event.preventDefault();
            toggleSelect($(this));
        }
        if (event.keyCode === 38) { //Up
            event.preventDefault();
            choosePreviousItem($(this));
        }
        if (event.keyCode === 40) { //Down
            event.preventDefault();
            chooseNextItem($(this));
        }
    });
});

/* METHODS ************************************************************************************************************/

function toggleSelect(select) {
    if (select.hasClass('expanded')) {
        select.toggleClass('expanded');
        select.children('.option').removeClass('shown');
    } else {
        select.toggleClass('expanded');
        select.children('.option').each(function () {
            const item = $(this);
            const select = item.parent();
            if (item.attr('value') !== select.attr('value')) {
                item.toggleClass('shown');
            }
        });
    }
}

function collapseSelect(select) {
    select.removeClass('expanded');
    select.children('.option').each(function () {
        $(this).removeClass('shown');
    });
}

function chooseNextItem(select) {
    collapseSelect(select);
    if (select.attr('value') !== '') {
        const selectedItem = select.children('div[value=\'' + select.attr('value') + '\']');
        const nextSibling = selectedItem.next('.option');
        if (nextSibling) {
            select.attr('value', nextSibling.attr('value'));
            select.children('.visual-option').html(nextSibling.html());
        }
    } else {
        selectFirstItem(select);
    }
}

function choosePreviousItem(select) {
    collapseSelect(select);
    if (select.attr('value') !== '') {
        const selectedItem = select.children('div[value=\'' + select.attr('value') + '\']');
        const prevSibling = selectedItem.prev('.option');
        if (prevSibling) {
            select.attr('value', prevSibling.attr('value'));
            select.children('.visual-option').html(prevSibling.html());
        }
    } else {
        selectFirstItem(select);
    }
}

function chooseItem(item) {
    const select = item.parent('.crossbrowser-select');
    select.children('.visual-option').html(item.html());
    select.attr('value', (item.attr('value')));
}

function selectFirstItem(select) {
    const firstItem = select.children('.option').first();
    select.attr('value', firstItem.attr('value'));
    select.children('.visual-option').html(firstItem.html());
}

/* Events *************************************************************************************************************/

function crossbrowserSelectOnClickEvent() {
    toggleSelect($(this));
}

function crossbrowserSelectItemOnClickEvent() {
    chooseItem($(this));
}

function crossbrowserSelectOnMouseWheelDownEvent() {
    chooseNextItem($(this));
}

function crossbrowserSelectOnMouseWheelUpEvent() {
    choosePreviousItem($(this));
}

function crossbrowserSelectOnFocusOutEvent() {
    collapseSelect($(this));
}
.crossbrowser-select {
    text-align: center;
    cursor: pointer;
    border: 1px transparent solid;
    border-bottom: 1px solid #70ccd9;
    border-radius: 10px;
}
.crossbrowser-select.expanded {
    color: #70ccd9;
    border-top: 1px solid #70ccd9;
}
.crossbrowser-select:hover,
.crossbrowser-select:focus,
.crossbrowser-select:active {
    outline: none;
    border: 1px solid white;
    background-color: transparent;
}

.crossbrowser-select > .option {
    display: none;
    color: white;
}
.crossbrowser-select > .option.shown {
    display: block;
}
<html>

<head>
  <title></title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>

<body style="background-color: black; color: white; padding: 50px">
  <div class="col-4 text-center">
    <div style="margin-bottom: 20px">Previous random element</div>
    
    <div value="" class="crossbrowser-select"  tabindex="0">
      <div class="visual-option">Select Item from list</div>
      <div class="option" value="1option">Option1</div>
      <div class="option" value="2option">Option2</div>
      <div class="option" value="3option">Option3</div>
    </div>
    
    <div style="margin-top: 20px">Next random element</div>
  </div>
  
  <script src="https://code.jquery.com/jquery-1.12.3.js" ></script>
</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When using Italics, the conflict arises between the specified line-height and the actual height of the

Recently, I encountered an issue that has me a bit perplexed: I have a span element with line-height set to 18px and font-size at 16px. Everything works perfectly when the text inside is regular; the height of the span remains at 18 pixels. The problem a ...

Despite changes in the state they are set to, the InitialValues remain constant

I am facing an issue with a Semantic-UI modal that includes a redux-form as its content. The form is passed to the modal when it opens, and the form element has an initialValues prop mapped to state. <FormModal handl ...

Ensure Safari sends the Origin header in jQuery GET requests

When I send a request from https://app.example.com, the following code is executed: $.get('https://api.example.com', { foo: 'bar' }) .success(getSuccess) .error(getError); This script runs smoothly on Chrome and Firefox, however, ...

What are the steps to create a dynamic navigation bar in React without encountering hydration issues?

My goal is to dynamically show or hide links based on user authorization. Here's my initial approach: const Navbar = () => { const { canDo, ...} = useUser(); //A Zustand store return ( <> <div> <ul> ...

What is the method for obtaining the WordPress user ID?

I am looking to incorporate a Twitter follow button for all site authors on every post. Below is the structure of the Twitter button: <a href="https://twitter.com/twitterapi" class="twitter-follow-button" data-show-count="false" data-lang="en">Foll ...

Determine the number of items (within an array) that were created within the past few days, weeks, and months leading up to the 'current time'

Having an array filled with objects containing timestamps: Here is a glimpse of the data: const dataList = [ { _id: "602102db3acc4515d4b2f687", createdDt: "2021-02-08T09:22:35.000Z", }, { _id: "6021024da706a260d89 ...

Find the item in the pop-up window

When removing a user from my list, a JavaScript popup pops up prompting to confirm the action with two buttons "OK" / "Annuler" : https://i.sstatic.net/BEdH2.png Is there a way to use Selenium to find and interact with these buttons? ...

employ the value of one array in a different array

Currently, I am working with an array (const second) that is being used in a select element to display numbers as dropdown options {option.target}. My question is: Is there a way to check within this map (that I'm using) if the 'target' from ...

The jQuery library triggers an error that can only be resolved by refreshing the

I am currently experiencing an issue with my form (form links are provided below, specifically referring to form1). The problem arises when I include jquery.js, as it fails to load the doAjax and getIP functions that are contained in a separate js file nam ...

I'm looking to showcase the list in a navigation bar by clicking on the hamburger menu. I want to include the 'home' and 'about' text specifically

Having trouble implementing the hamburger menu functionality in my HTML/CSS project. When clicked on a shrunken screen, I want the 'Home' and 'About' text in the nav to appear stacked on top of each other. JS is causing me some difficul ...

Using mongoose to differentiate whether an update-upsert operation is performing an insert or an update

Is the "upsert" option for updating working correctly? I attempted to upsert an object into mongodb twice with the same key, but did not receive an inserted message. Am I overlooking something? (mongodb : v2.6.3; mongoose : 3.8.15) Member.findOneAndRemov ...

The process of authenticating route parameters in Nuxt

I'm having trouble validating route parameters in my page component using the following code: async validate({ params, store }) { await store.dispatch(types.VALIDATE_PARAMS_ASYNC, params.id) } And here's the corresponding code in the store: ...

Leveraging JavaScript functions for invoking Ajax requests, accompanied by ASP.NET controls

Having a background in PHP, I am accustomed to using a PHP file to handle all of my ajax calls. Recently, I have been introduced to ASP.NET controls and the overall environment. I am curious about the correct method for handling ajax requests when they n ...

The placeholder feature seems to be malfunctioning when it comes to entering phone numbers in a react

I am working on a MUI phone number form field. I want the placeholder to show up initially, but disappear when the user starts typing. How can I achieve this functionality in my code? import React from "react"; import MuiPhoneNumber from " ...

Unregistering an event with AngularJS

Exploring the functions of a controller named MyCtrl: class MyCtrl { constructor($scope, $rootScope, ...) { this.$scope = $scope; this.$rootScope = $rootScope; this.doThis = _debounce(this.resize.bind(this), 300); ... ...

Is it necessary to encode special characters in a JSON object?

I am currently working on a code where I am taking a class and converting it to JSON format. Throughout my testing, all the content is surrounded by double quotes, for example: { "a" : "hello world ! '' this is john's desk" } I am wonderi ...

What are some effective ways to align an image to the left and text to the right within a table

I need to display a member with a higher rank, showing the user image along with their username. However, I am struggling to align the image and text properly due to varying username lengths causing them to appear in a zig-zag position. Here is what I hav ...

Encountering an issue when trying to use SVG clip-path in Safari

I'm currently experimenting with creating a unique hexagonal border around a button. My approach involves enlarging the container element by a few pixels compared to the button size and using the same clip-mask on both elements to achieve a bordered e ...

Retrieving JSON information from asynchronous JavaScript and XML (AJAX)

I am struggling with making a URL that contains JSON Data work properly. The issue lies in the data field - I am unsure of what to input here as it is currently undefined. My goal is to store an array of the JSON data received from the ajax request. What ...

change visibility:hidden to visible in a css class using JavaScript

I've put together a list of Game of Thrones characters who might meet their demise (no spoilers included). However, I'm struggling with removing a CSS class as part of my task. Simply deleting the CSS is not the solution I am looking for. I' ...