CSS: Achieving vertical centering without specifying a fixed height using line-height. Is it possible?

Using line-height to vertically center text within an inline-element is a technique I often employ.

Here's a demo I created:

body,
section {
  width: 100%;
}

section {
  background-color: lightGrey;
}

#wrap {
  margin: 30px auto;
  width: 100%;
  max-width: 800px;
  text-align: center;
  height: 48px;
}

.my-element {
  line-height: 48px;
}
<section>
  <div id="wrap">
    <span class="my-element">My element</span>
  </div>
</section>

It works well, with the text perfectly centered vertically within the grey bar.

However, the drawback of this method is having to fix the parent-element's height.

Is there a more dynamic approach for achieving the same result?

An approach that won't break when the parent-element's height changes?

Answer №1

If you want to center elements both vertically and horizontally using Flexbox, you can simply apply align-items: center and justify-content: center.

section {
  background-color: lightGrey;
}

#wrap {
  margin: 30px auto;
  width: 100%;
  max-width: 800px;
  text-align: center;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
}
<section>
  <div id="wrap">
    <span class="my-element">My element</span>
  </div>
</section>

Answer №2

Remove the height functions to eliminate the space between the span and div, then add padding like padding: 10px 0px 10px 0px;. Another option is to use padding: 10px; for a less specific approach.

body,
section {
  width: 100%;
}

section {
  background-color: lightGrey;
}

#wrap {
  margin: 30px auto;
  width: 100%;
  max-width: 800px;
  text-align: center;
  padding: 10px 0px 10px 0px;
}
<section>
  <div id="wrap">
    <span class="my-element">My element</span>
  </div>
</section>

Answer №3

You can utilize the CSS property transform: translate to achieve the desired effect, and for more options, refer to the duplicate link.

body,
section {
  width: 100%;
}

section {
  background-color: lightGrey;
}

#wrap {
  position: relative;
  margin: 30px auto;
  width: 100%;
  max-width: 800px;
  text-align: center;
  height: 48px;
}

.my-element {
  position: relative;
  display: inline-block;
  top: 50%;
  transform: translateY(-50%);
}
<section>
  <div id="wrap">
    <span class="my-element">My element</span>
  </div>
</section>

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

What is the best method to transfer and incorporate essays and information onto my HTML page?

Here are some unique events and observances for the month of December: DECEMBER 1 World AIDS Day National Pie Day National Eat a Red Apple Day Bifocals at the Monitor Liberation Day Day With(out) Art Day Rosa Parks Day DECEMBER 2 International Day for th ...

How can an HTML form element identify which submit button has been clicked?

In my HTML form, I have included 2 buttons to meet the requirements of our customers. I am trying to determine how to identify which button was pressed on the backend. Below is a code snippet that demonstrates this: <form method="get"> < ...

Can floating elements be disregarded by block elements?

According to W3C, the behavior of floating elements is such that: When a float is present, non-positioned block boxes that come before and after the float flow vertically as if the float doesn't exist. However, line boxes positioned next to the fl ...

Can you explain the process of NuxtJS css extraction for creating static websites?

I am currently working on creating a static website using my minimal code with Nuxt. This code includes integration of the tailwindcss toolkit and vue2-leaflet. When I run nuxt generate I end up with two CSS files - one for the tailwindcss styles and an ...

What is the best method for eliminating tiny spaces between images that are aligned horizontally?

Check out this link for more details: . I am looking to eliminate the slim vertical gaps between the images in html5 without resorting to using the table cellpadding="0" cellspacing="0". Any ideas on how to achieve this? ...

Having difficulty displaying data in the proper format with two-way binding

In the realm of my webpage, I have a plethora of headings, paragraphs, images, and other data at my disposal. From the backend, a dataset is provided to me that includes an array with various properties housing the desired information. The challenge lies i ...

Replace text using the str_replace function

I have a total of seven lines of text that I need to manipulate using PHP. My first task is to filter out any lines that do not contain the word 'MARCO1998'. Next, from the remaining lines, I need to extract only the 1-3 numbers that come after ...

Tips for securing a navbar in material ui

https://i.stack.imgur.com/CYfmQ.png In my current React project, I am facing an issue with aligning components within the Material-UI AppBar Component. My aim is to achieve a seamless and perfectly straight alignment for three key elements: a logo image, ...

Ways to retrieve HTML content from various spans and incorporate the values as classes

Here is my custom HTML: <div class="box"> <ul class="fourcol first"> <li class="feature-item">Description: <span>0</span></li> <li class="feature-item">Description: <span>0</span></ ...

Arrange the <form:radiobuttons> in a vertical position

I'm currently utilizing Spring MVC's <form:radiobuttons> to showcase radio buttons: <form:radiobuttons path="selection" items="${arraySelection}" /> The issue I am facing is that it is displaying the radio buttons in a horizontal la ...

Ways to center text vertically within a cell in a Bootstrap 5 table

I am trying to achieve vertical alignment in one of the cells of a table I created. According to the Bootstrap 5 documentation, the vertical-alignment utilities only affect certain elements like inline, inline-block, inline-table, and table cell elements. ...

The Card Component from Core UI fails to appear in the Print Preview feature

I'm currently experimenting with the Card Component from the Core UI framework. However, I'm facing an issue where the color of the Card component and its associated icon do not appear in the Preview when trying to print the page. I attempted to ...

Utilize LESS Bootstrap as a guide for incorporating content

I have been struggling to properly integrate Bootstrap into my LESS file. Currently, I am adding Bootstrap to my project using NPM. If I simply use the following import statement in my LESS file: @import (reference) 'node_modules/bootstrap/less/boot ...

Display a div with a link button when hovering over an image

Currently, I'm attempting to display a link button within a div that will redirect the user to a specified link upon clicking. Unfortunately, my current implementation is not functioning as expected. I have provided the code below for reference - plea ...

Achieving Perfect Alignment for Absolutely Positioned Divs in

I'm currently facing an issue where the image I'm trying to center horizontally also moves the parent div downward when I try to vertically center it using top-margin. This is not the desired outcome. If you'd like to see what I mean, I&apo ...

What steps can I take to make sure a jQuery Mobile table does not become responsive?

My goal is to make a table responsive by using media queries to hide optional columns on smaller devices. I need to hide two columns based on different screen sizes: @media screen and (max-width: 33em) { th.optional-1, td.optional-1 { display: no ...

What is the correct way to properly wrap the div component in this code snippet?

I am currently working on implementing a Javascript component that displays pinned locations and related information on a map. I have made some progress with the implementation, but unfortunately, it does not appear correctly in the actual site. There is a ...

Images that adjust to different screen sizes within a grid layout

I have four images that need to be aligned in the following layout: ____________ |1 |4 | |_____| | |2 |3| | |__|__|______| They must be flush against each other, occupy 100% of the viewport's width, and most importantly, be respon ...

Applying ngClass to handle positive and negative numbers and adjust color in Ionic/Capacitor

I have data from my API that includes price and percentage data. I want to display negative numbers in red, and zero or positive numbers in green. After exploring Angular documentation, I found that ngStyle and ngClass can be used for this purpose. I chose ...

Using Javascript to extract and organize JSON arrays from various sets of checkboxes

Is there a way to automatically create an array of multiple groups of arrays like this: arr = {arr1:{index:value, index2:value2}, arr2:{index,value, index2:value2}}; The order is based on groups of checkboxes in HTML (see example below): <div class=& ...