Skip to content
Fix Code Error

How do I vertically center text with CSS?

March 13, 2021 by Code Error
Posted By: Anonymous

I have a <div> element which contains text and I want to align the contents of this <div> vertically center.

Here is my <div> style:

#box {
  height: 170px;
  width: 270px;
  background: #000;
  font-size: 48px;
  color: #FFF;
  text-align: center;
}
<div id="box">
  Lorem ipsum dolor sit
</div>

What is the best way to achieve this goal?

Solution

You can try this basic approach:

div {
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 2px dashed #f69c55;
}
<div>
  Hello World!
</div>

It only works for a single line of text though, because we set the line’s height to the same height as the containing box element.


A more versatile approach

This is another way to align text vertically. This solution will work for a single line and multiple lines of text, but it still requires a fixed height container:

div {
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 2px dashed #f69c55;
}
span {
  display: inline-block;
  vertical-align: middle;
  line-height: normal;
}
<div>
  <span>Hello World!</span>
</div>

The CSS just sizes the <div>, vertically center aligns the <span> by setting the <div>‘s line-height equal to its height, and makes the <span> an inline-block with vertical-align: middle. Then it sets the line-height back to normal for the <span>, so its contents will flow naturally inside the block.


Simulating table display

And here is another option, which may not work on older browsers that don’t support display: table and display: table-cell (basically just Internet Explorer 7). Using CSS we simulate table behavior (since tables support vertical alignment), and the HTML is the same as the second example:

div {
  display: table;
  height: 100px;
  width: 100%;
  text-align: center;
  border: 2px dashed #f69c55;
}
span {
  display: table-cell;
  vertical-align: middle;
}
<div>
  <span>Hello World!</span>
</div>

Using absolute positioning

This technique uses an absolutely positioned element setting top, bottom, left and right to 0. It is described in more detail in an article in Smashing Magazine, Absolute Horizontal And Vertical Centering In CSS.

div {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  width: 100%;
  border: 2px dashed #f69c55;
}
<div>
  <span>Hello World!</span>
</div>
Answered By: Anonymous

Related Articles

  • Navbar not filling width of page when reduced to mobile view
  • Active tab issue on page load HTML
  • center 3 items on 2 lines
  • Footer not staying at the bottom when scrolling
  • How do I keep only the first map and when the game…
  • Regex on htaccess file gives INTERNAL REDIRECT error
  • Pandas pivot_table: filter on aggregate function
  • How to show title in hover - css / jquery
  • Is it possible to apply CSS to half of a character?
  • Azure Sql : Unable to Replace HTML String
  • Centering in CSS Grid
  • insert tables in dataframe with years from 2000 to…
  • Unresponsive hamburger icon in HTML
  • Having trouble with my nav bar/header, It used to…
  • Why my "title" bloc doesn't go to bottom?
  • How to use html template with vue.js
  • Web colors in an Android color xml resource file
  • How do i update a javascript variable as its value changes?
  • Open/Close content and anchor link
  • Adobe XD to responsive html
  • CSS Input with width: 100% goes outside parent's bound
  • Increasing size of semi circle using css
  • Jquery fadeToggle Trouble
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • How do I do a drag and drop using jQuery to move…
  • Reset/remove CSS styles for element only
  • Link color is not changing after adding a class with jQuery
  • Vertical (rotated) text in HTML table
  • Daisy is overlapping the other contents of the div
  • SQL find sum of entries by date including previous date
  • Is it possible to move my text side by side with my icon
  • Cannot make table responsive
  • .map is not returning the values(not a function)
  • Add calculated column to df2 for every row entry in…
  • Bootstrap - center child when parent isn't centered…
  • I need to sum values with specific condition
  • How can I show the caption of a single grid item…
  • HTML5 best practices; section/header/aside/article elements
  • Paper-dialog shows up behind drawer-panel when…
  • Show scroll update when scrolling down page
  • Obtain most recent value for based on index in a…
  • My DIV elements go diagonal instead of horizontal
  • Fix top buttons on scroll of list below
  • HTTP Status 500 - org.apache.jasper.JasperException:…
  • How do I make responsive images?
  • Generating PDF file with Images in flutter
  • "Next" Arrow Disappearing Too Early in Carousel
  • Checkbox filtering with VueJS
  • CSS Variable trough Polymer (dynamically loaded) elements
  • Sort table rows In Bootstrap
  • Make Flip Card HTML CSS
  • iOS UICollectionViewCell resizable dashed border
  • How to change the color of vaadin-select-text-field…
  • Only show HTML body after a CSS animation is…
  • property flex-wrap not working correctly?
  • How to get the same space between text and block
  • Applying an ellipsis to multiline text
  • Subquery on SELECT with conditional WHERE clause after it
  • I cant get my type writer heading to the center of my code
  • Why doesnt my table sort my div variable in numerical order?
  • CSS Grid Layout not working in IE11 even with prefixes
  • How to prevent scrolling the whole page?
  • Why is my SwiftUI view not updating when the model changes
  • How do I make a WPF TextBlock show my text on…
  • In CSS Flexbox, why are there no "justify-items" and…
  • Bootstrap 4.6 + CSS, how to bottom align a row
  • Best way to extract messy HTML tables using BeautifulSoup
  • Oracle sql query to group two sets of dates if sequencials
  • how to use canvas in JavaScript flappy bird code
  • How to create a value which can be repeatedly used…
  • Adding multiple dropdown menu's next to each other…
  • How do I center content in a div using CSS?
  • div "container" which does not center correctly
  • Create HTML with inline CSS(including color, font…
  • Why is there a tiny indent on the left side of the footer?
  • How to specify line breaks in a multi-line flexbox layout?
  • Triggering text area by clicking related select/checkbox
  • Vuetify grid system row management
  • How to stretch the div to all the height of the page?
  • Why is it that "No HTTP resource was found that…
  • Moving average in MYSQL without dates but grouped by…
  • Content showing over the top of tooltip
  • Nesting query results in BigQuery
  • How to create a game over screen for a basic HTML/JS game?
  • Trouble with boxes appearing/hiding based on selection
  • Text border using css (border around text)
  • How to add fade animation for this tab
  • Python Monthly Change Calculation (Pandas)
  • Setting display to none with Javascript
  • Regex needed to match a proper currency format of…
  • Why does I can't add background image even I use static
  • Why my first title isn't center like the second title?
  • VueJS masonry layout
  • How to use 2 columns as "key" to get MAX value of…
  • Python - Modifying rows of a data frame where the…
  • Do not close the mode in the mouse up event
  • Javascript validate all checkboxes are selected
  • Pandas / Python - Compare numerically each row with…
  • How to display and transition when scroll position…
  • Polymer 1.0 Trying to make a splitter which works…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Converting integer to string in Python

Next Post:

How do I include a JavaScript file in another JavaScript file?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error