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

The header section on a website not behaving as expected in the Chrome browser

For my website, I want it to look like this in Internet Explorer: https://i.stack.imgur.com/hSkVM.png ^^ This is the IE view However, in Chrome, it displays like this: https://i.stack.imgur.com/noQw8.png The issue is with the Top bar on Chrome showing co ...

After refreshing, a blank page appears when using the HTML POST method

After conducting a test using an HTML form with the POST method, I encountered an unexpected outcome. The setup involved two HTML pages hosted on an Apache server (with PHP already installed): post.html and target.html. Below are the code snippets for thes ...

Ways to set each tinymce editor as standard excluding a few selected ones

Currently, I am utilizing TinyMCE as my text editor for a specific project. Within the header of my codebase, I have specified that all <textarea> elements should be rendered with TinyMCE functionality. By default, these text areas have a height of 3 ...

Is it possible to dynamically add elements in AngularJS without relying on directives?

As a newcomer to Angularjs and not very fluent in English, I embarked on the journey of adding <li> using directives. You can see the result of my first attempt at this link. Next on my list was mastering two-way binding by passing values between th ...

Set the class of an element dynamically using ng-class and detect changes with ng-change

I want the input field to initially have the class .form-control-error. When the user clicks on the field and starts typing, I would like it to change to .form-control-success. I attempted the following code but couldn't get it to update. The ng-chan ...

Experience seamless video playback on both mobile and web browsers with JW Player

I have integrated the JW Player for video playback on both mobile and web browsers. Currently, I have a library of 100 videos with dimensions set at 1280*700 pixels. These videos work well on web browsers and load quickly depending on internet speed. Howe ...

When I test my jQuery scripts in jsfiddle, they run smoothly. However, they do not seem to work properly when I

My code is almost perfect, but the jQuery function is giving me trouble. It works fine in jsfiddle, but for some reason, it's not functioning in my HTML file. I don't believe extra characters are being added when copying from the HTML file. I hav ...

Adjusting div height as you scroll down the page

Hello, I am new to CSS and I have encountered an issue with setting the height of a div element to 100%. When the list on my page exceeds the size of the page, the div is no longer visible when scrolling. Do you have any ideas on how to fix this? Here is t ...

Can an input element be used to showcase a chosen image on the screen?

I would like to display the selected image from an input element. Can this be done with a local file, accessing the image on the client side, or do I need to upload it to a server? Here is my React code attempt: I can retrieve the correct file name from t ...

How to Add Catchy Titles to Your Menu Items on Silverstripe CMS?

Hey there! I'm currently working with Silverstripe CMS using the "Simple" template. I'm interested in finding out how to add subtitles to my menu items. Here's the current structure of my navigation template: <nav class="primary"> &l ...

Using Javascript/HTML to enable file uploads in Rails

I'm currently facing an issue with uploading and parsing a file in Rails, as well as displaying the file content in a sortable table. I followed a tutorial on to get started. This is what my index.html.erb View file looks like: <%= form_tag impo ...

display and conceal a division by clicking a hyperlink

How can I make a hidden div become visible when clicking on a specific link without using jQuery? Javascript function show() { var a = document.getElementsByTagName("a"); if (a.id == "link1") { document.getElementByID("content1").style.v ...

Trouble with bringing in the solana/web3.js library

After successfully importing the solana/web3.js package and running it within a NodeJS file, everything was working fine. However, things took a turn when attempting to connect this file with basic HTML, resulting in an error being thrown. import { Tra ...

Cells within a table are equivalent

I am attempting to ensure that all table cells match the size of the image, but for some reason, they are not aligning properly. Visit this link for reference. Here is a condensed version of the HTML code: <table> <tr> <td> ...

Tips for transferring data to the next page with JavaScript AJAX

I am working on a webpage that includes an html select element <pre> $query = mysql_query("select * from results"); echo "<select id='date' onchange='showdata()' class='form-control'>"; while ($arr = mysql_fetch_a ...

What is the maximum number of files that FileUploader can accept when multi-select is enabled?

I encountered the following issue: A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll Additional information: Maximum request length exceeded. while attempting to upload 250 JPEG files, each around 98 KB in ...

Looking for assistance with CSS positioning techniques

Creating a dropdown list with a caret icon for each item is my goal, but I'm facing some challenges. Here's the code snippet of the div structure: <div class="class-to-div1" id="{{ div.id }}" data-cardsnum="{{ div.num }}"> <div clas ...

Adjusting the position of the parent div by manipulating the bottom property

Is there a way to toggle the bottom property of a div when clicking its child anchor tag? <div class="nav" :class="{ 'full-width': isFullWidth }"> <a class="toggle-button" @click="toggleNav"><i class="fa fa-angle-down">< ...

Creating a CSS grid layout with dual columns to dynamically adjust and accommodate two items in each row

I am attempting to create this layout using CSS grid: The goal is to have an input and a textarea. The textarea should be of the size of 2 inputs. If there is already a textarea in the previous column, the next column should accommodate 2 inputs. The numb ...

Playing only audio and no video in an Android WebView using HTML5

I am currently facing a challenge with a webpage that includes an html5 video and css3 animations. While the web page functions perfectly on an android device's browser, I am experiencing laggy, glitchy, and jumpy animations when using hardware accele ...