Attempting to vertically center text within a percentage div

I'm trying to create a button that is centered on the screen with text aligned vertically within the button. I want to achieve this using CSS only and restrict the usage of percentages only. Here's what I have so far:

Check out my code snippet here

HTML

<div id="outer">
    <div id="button">
        button text
    </div>
</div>

CSS

body {
    margin : 0px;
}
#outer {
    position : absolute;
    width : 100%;
    height : 100%;
    background-color : #123456;
    text-align: center;
}
#outer:before {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}
#button {
    height : 50%;
    width : 50%;
    background-color : #FFFFFF;
    display: inline-block;
    vertical-align: middle;
}

Answer №1

In today's web design, it's best to use display properties and keep things in the flow. Absolute positioning is considered outdated :)

For example, you can try using display:table.

html, body {
    height:100%;
    width:100%;
    margin:0;
}
html {
    display:table;
}
body {
    display:table-cell;
    vertical-align:middle;
    background:#48a
}
#button {
    height: 50%;
    width: 50%;
    background-color: #FFFFFF;
    margin:auto;
    text-align:center;
}
/* Improved way to vertically center pseudo element */
#button:before {
    content:'';
    height:100%;
    ;
    vertical-align:middle;
    display:inline-block;
}

You can also explore using display:flex in your layouts.

html, body {
    height:100%;
    width:100%;
    margin:0;
}
body {
    display:flex;
    background:#48a
}
#button {
    height: 50%;
    width: 50%;
    background-color: #FFFFFF;
    margin:auto;
    text-align:center;
}
/* Improved way to vertically center pseudo element */
# button:before {
    content: '';
    height: 100%; ;;
    vertical-align: middle;
    display: inline-block;
}

If you want to apply flex display to the button box as well, you can add these rules and remove the pseudo element:

#button {
    height: 50%;
    width: 50%;
    background-color: #FFFFFF;
    /* To center itself in flex box */
    margin: auto;
    /* To center inside content */
    justify-content: center;
    display: flex;
    align-items: center;
}

display:flex; is supported by latest versions of Opera, Chrome, Firefox, and IE.

display: table; works with most browsers, including IE8 and above.

Answer №2

If utilizing flexbox is an option, a practical and tidy solution would be as follows:

Include the following code in the #outer container to centrally align the button div:

#outer {
  ...
  display: flex;
  align-items: center;
  justify-content: center;
}

Then, apply the following styles to the #button to align the text within:

#button {
    ...
    flex: 0 0 auto;
    display: flex;
    align-items: center;
    justify-content: center;
}

It is also necessary to remove the display: inline-block; property from inside #button.

Here's a working fiddle (tested on Firefox and Chrome on MacOS): http://jsfiddle.net/8BJ94/53/

For a comprehensive overview of flexbox support, you can refer to this resource: http://caniuse.com/flexbox

Answer №3

Another way to experiment with display table-cell without relying on pseudo selectors is shown below:

<div class="container">
    <div class="box">
        <div id="button">click me</div>
    </div>
</div>
html, body {
    height:100%;
}
.container {
    display:table;
    height:100%;
    text-align:center;
    border:1px solid blue;
    width:100%;
}
.box {
    display:table-cell;
    vertical-align:middle;
    border:1px solid orange;
}
#button {
    background-color : #00f;
    display: inline-block;
    vertical-align: middle;
    padding:50px;
}

http://jsfiddle.net/8BJ94/57/

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

HTML5, canvas covering every element

Below is the code that I am working with: <html> <head> <title>canvas</title> </head> <body> <canvas width="1745" height="569" style="width: 1730px; height: 1680px; position: absolute; z-index: 1"></canvas> ...

Using a single jQuery script, implement multiple modals on a webpage that are responsive on both desktop and mobile devices

My Modal is functioning well on desktop, but I'm facing an issue on mobile where the screen doesn't close when clicking outside the modal area. Is there a way to solve this for mobile without adding the 'X' button to close it? I attem ...

The properties of the NextFont variable cannot be utilized in the CSS global scope when using the var() function

// font.ts file import { Quicksand, Syncopate } from 'next/font/google'; export const quickSandRegular = Quicksand({ subsets: ['latin'], variable: '--font-quicksand-reg', weight: '400', display: 'swap& ...

Unlocking the Potential of Larger jQuery Icons

In a recent announcement, the jQuery team unveiled new icons for their UI components. However, I have been unable to locate any examples of how to use them or where they can be downloaded from. Also, it appears that the themes in the ThemeRoller only provi ...

Issues with the menu pop-up functionality arise when utilizing the CSS class .active

When I have this code, the ".active" function doesn't work when clicked. However, if I change the div class from "top-menu-popup" to "top-menu-popup active" when opening the page, the menu is already activated. <div class="top-menu-popup"> ...

How can I achieve a full-width stepper in Bootstrap?

.row { background: #f8f9fa; margin-top: 20px; } .col { border: solid 1px #6c757d; padding: 10px; } <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/> <link href="https://useloope ...

Utilizing flexbox, absolute positioning, and 100% height in web design

While experimenting with a flexbox inside an absolute box within a div of defined height, I encountered a problem. Let me explain the issue step by step. Here is a link to a fiddle demonstrating the problem: https://jsfiddle.net/8ub9tyub/ When hovering o ...

Rings that react to both width as well as height

Below is a popular CSS markup for creating responsive circles. http://jsfiddle.net/WTWrB/355/ <div class="circle"></div> .circle { width: 25%; height:0; padding-bottom: 25%; -moz-border-radius: 50%; -webkit-border-radius: ...

Creating an intricate table layout using AngularJS and the ngRepeat directive

I'm attempting to create a table similar to the one shown in the image below using HTML5. In this table, there is a multi-dimensional matrix with Class A and Class B highlighted in yellow. Each class has three modes (highlighted in blue), and each mo ...

Issue with toggling in react js on mobile devices

Currently, I am working on making my design responsive. My approach involves displaying a basket when the div style is set to "block", and hiding it when the user browses on a mobile device by setting the display to "none". The user can then click on a but ...

Enhancing design precision from Figma to flawless pixels

I'm facing the challenge of converting a figma design into an HTML and CSS template with a fixed dimension of 1440px. I'm unsure about where to begin coding in terms of screen size - should I start at 1440px and scale down/up, or begin with mobil ...

The H1 tag is mysteriously displaying padding or margin on the bottom, despite not being set

Despite not setting any padding or margin for the H1 tag, it still appears to have some spacing at the bottom. After applying a margin and padding of 0 to both the h1 tag and the text below it, I am still facing an issue where the text doesn't align ...

ui-grid row size set to automatically adjust using rowHeight : 'auto'

Has anyone else experienced this strange behavior with ui-grid? When I set the rowHeight to auto, each cell in the same row ends up with different heights. One of the cells contains multiline data, which seems to be causing issues for ui-grid. I've ev ...

Guide to making a toggle button with a Light/Dark mode functionality

I have implemented a light/dark toggle button and now I want to integrate the functionality for switching between light and dark themes on my webpage. The switch should toggle the theme between dark and light modes when clicked. Some basic styling has been ...

How can we programmatically trigger a click action on an element obtained through an HTTP request with the help of Set

window.addEventListener("load" , () => { setInterval(() => { let xhttp = new XMLHttpRequest(); xhttp.open("GET", "./messagedUsers.php", true); xhttp.onload = () => { if(xhttp.re ...

Adding a click function to a div individually when they share the same class in HTML

My goal is to include 4 unique divs inside a timeline container: This is how I envision the structure: <div id="timeline" > <div class="timeline-bar t-1"></div> <div class="timeline-bar t-2"> ...

Is BEM mandating the creation of superfluous elements?

<header> <a href="#"><img src="kitty.jpg" /></a> ... </header> In the context of organizing for BEM, take this example within the header section that is not dependent on the header block. To adhere to BEM guidelines, I op ...

The use of Material-UI collapse animation in a table results in the insertion of div elements, triggering a validateDOMNesting warning

Having a data-filled table, I am looking to implement smooth transitions when adding or deleting an item. This is a ReactJS project utilizing Material-UI. The desired effect is similar to the one demonstrated in their example. While they use a List compon ...

What is the best way to eliminate the left padding on a TimelineItem component?

When using the Timeline component to display information, there are three columns: TimelinItem, TimelineSeparator, and TimelineContent. I tried setting the padding of TimelineItem to 0 but it didn't work. The <Trace/> component is a sub-compone ...

Is there a way to use HTML and CSS to switch the style of a dynamic decimal number to either Roman numerals or Katakana characters within a specified HTML element, such as a tag, div

I've searched everywhere but only found guides on list styling and counter styling in CSS that didn't work out. So, for example, I have a number inside an HTML tag that is changed dynamically using Vue Watch. I want to display the number in upper ...