What is the best way to align text in the center of a div?

I just created this dropdown menu, but I am encountering an issue.

Whenever I resize the div or h4 element, the text ends up at the top. Even after trying to solve it with text-align: center;, the problem persists.

Here is a visual representation of what I am aiming for:

See Imgur image

Below is the CSS code used for styling:


#alue_search {
  box-sizing: border-box;
  background-image: url('https://cbot.me/images/alue_icon.png');
  background-position: 14px 12px;
  background-repeat: no-repeat;
  font-size: 16px;
  padding: 14px 20px 12px 45px;
  border: none;
  color: #353535;
  border-radius: 5px 5px 0px 0px;
}

#alue_search:focus {
  outline: none;
}

.dropdown {
  display: inline-block;
  position: relative;
  background-color: #f6f6f6;
  min-width: 230px;
  z-index: 1;
  border-radius: 5px;
  border: 3px solid #ddd;
}

.dropdown-content {
  position: relative;
  z-index: 1;
}

.dropdown-content h4 {
  height: 35px;
  background-color: #fff;
  border: none;
  border-radius: 5px;
  color: #353535;
  transition: all 0.3s ease-in-out;
  display: none;
}

.dropdown-content h4:hover {
  background-color: #ddd;
  cursor: pointer;
}

.dropdown-content div {
  height: auto;
}

.show {display:block;}

If you require the HTML part as well, here it is:

<div class="dropdown">
      <div id="myDropdown" class="dropdown-content">
        <input type="text" placeholder="Search area" id="alue_search" onkeyup="filterFunction()">
        <div onclick="select('Helsinki')"><h4>Helsinki</h4></div>
        <div onclick="select('Jyväskylä')"><h4>Jyväskylä</h4></div>
        <div onclick="select('Kuopio')"><h4>Kuopio</h4></div>
      </div>
</div>

Answer №1

The simplest way to achieve this is by using the line-height property on your h4 element to vertically center the text.

.dropdown-content h4 {
    line-height: 35px;  // Centering vertically
    text-align: center; // Centering horizontally

    // Additional styling goes here
}

https://i.stack.imgur.com/yCOcM.png

Answer №2

To make it both vertically and horizontally centered, use the following CSS:

.dropdown-content h4 {
  height: 35px;
  ...
  text-align:center;
  line-height:35px;
}

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

The React component designed to consistently render video frames onto a canvas is unfortunately incompatible with iOS devices

I'm facing an issue with my code snippet that is supposed to draw video frames on a canvas every 42 milliseconds. It's working perfectly on all platforms and browsers except for iOS. The video frames seem unable to be drawn on canvas in any brows ...

Guide on restricting the character count and displaying the leftover characters using PHP with Ajax

I've been working on implementing a feature to display the remaining characters in a PHP AJAX call. I was successful using JavaScript, but I'm having trouble doing it with AJAX in PHP. Can someone provide assistance? <script type="text/javasc ...

Why does my chart.js disappear every time I perform a new render?

Hey there, I'm facing an issue with my code. Let me paste what I have... import React, { memo, useEffect } from 'react'; import Chart from "chart.js"; /* redux-hook */ import { useSelector } from 'react-redux' const lineChart = m ...

Tips for avoiding HTML <tags> in the document.write function

I am trying to paint the actual HTML code within a tag using JavaScript but escaping it doesn't seem to be working. function displayHTMLString(n){ document.write("'<table>'"); for (i in range(0,n)){ ...

Develop a fresh class by inheriting from HTMLDivElement and expanding its prototype

My goal is to add a new method to the HTMLDivElement prototype without cluttering the HTMLDivElement itself with my custom methods. This has led me to attempt creating a new class that extends the HTMLDivElement. export class ScrollableElement extends HTML ...

Ways to verify the element prior to the completion of the request?

Utilizing Angular and Playwright Within my application, I have incorporated 2 buttons - one for delete mode and another for refreshing. Whenever the user triggers a refresh action, the delete mode button is disabled. Once the request returns, the delete m ...

Looking to extract the hidden value from an HTML input field using Selenium

Unable to retrieve the value of a hidden element in HTML, even though it is displaying. Seeking assistance in accessing the value despite the type being hidden. <input type="HIDDEN" label_value="Sub Reference" title="Sub Reference" id="ACC_NO" dbt="BK_ ...

Achieving an italicized appearance throughout an HTML document

I recently downloaded a sample page from the Mathjax website and acquired their package from Github to use it locally. In addition, I wanted to incorporate the computer modern font, so I unzipped the file containing ttf files into fonts/cmu. Here's ...

I'm encountering an undefined JavaScript variable, how should I proceed?

$(function(){ //Location was "set". Perform actions. $("#geocodesubmit").click(function(){ var geocoder = new google.maps.Geocoder(); geocoder.geocode( { 'address': address}, function(results, status) { if (status ...

What is the best way to update a page and retrieve fresh data from a service in Angular?

On my webpage, there is a table and two charts coming from three different controllers. I am looking for a way to refresh all of them simultaneously by clicking on a single refresh button. This will allow the data to be fetched from the webservice again an ...

Parsing JSON data repeatedly using JavaScript within an HTML environment

The following code I found on a popular web development website works perfectly: <!DOCTYPE html> <html> <body> <h1>Customers</h1> <div id="id01"></div> <script> var xmlhttp = new XMLHttpRequest(); var url ...

There is an error in ReactJS: TypeError - _this.props.match is not defined

I am experiencing a TypeError in my console tab and I can't seem to figure out where the error is occurring in my source code. I am relatively new to ReactJS so any help in identifying what I'm doing wrong would be greatly appreciated. Thank you ...

Tips for efficiently sending multiple ajax requests

Seeking help with my ajax knowledge. Currently, I have a function that is supposed to insert multiple items into an SQL database using a PHP page. However, it seems to only be inserting the last item entered. Here's the code snippet: function submitI ...

How to execute a JavaScript function within PHP code

Hey there, seeking some assistance. On my main page index.php, I have a simple js function named function1() that opens test.php as a pop-up window when clicked. The content in this pop-up window comes from another page called p1.php. Now, I need to set it ...

An error was encountered in the JSON syntax: Unexpected symbol <

I have encountered a problem with my code that I cannot seem to resolve. Despite the JSON data being successfully sent to the backend and processed correctly, the success function of the call is never triggered. Here is the snippet of my function: Regist ...

"Designing with Vue.js for a seamless and adaptive user experience

I'm looking to customize the display of my data in Vuejs by arranging each property vertically. Instead of appearing on the same line, I want every item in conversationHistory to be displayed vertically. How can I achieve this in Vuejs? Can anyone off ...

How can I create a more spacious and stylish JTextField for my address bar?

I am working on developing my Java skills by creating a custom browser. Is there a way to adjust the size and shape of the address bar, which is currently implemented as a JTextField with Swing's default settings? Here is the code snippet I am using: ...

Can the orientation of the card reveal be customized in Materializecss?

Exploring the card-reveal feature in the materializecss framework on this page: https://codepen.io/JP_juniordeveloperaki/pen/YXRyvZ with official documentation located at: In my project, I've rearranged the <div class="card-content"> to display ...

Presentation: Positioning Next Buttons Beside Slide Images While Maintaining Responsiveness

I am facing a challenge with my slideshow project. The slideshow consists of images and text on each slide, along with previous and next buttons that are aligned within the parent container. I am trying to align these buttons at the midpoint of each image ...

Establish a React component to observe socket.io

I am currently looking for the best way to connect my React component with socket.io in order to listen to events. My current approach involves including the following HTML code: <script src="socket.io/socket.io.js"></script> and then initial ...