Aligning content in the center vertically of a container

My attempt to vertically center some h2 text within a div using display:table-cell along with vertical-align: middle is not successful.

The issue seems to be arising because the div I want to center the content in is nested inside another div.

Below are my CSS and HTML code snippets:

.productList {
  width: 100%;
  max-width: 1120px;
  position: relative;      
  margin: 0 auto;
}
.hoverbase1 {
  float: left;
  margin: 15px;
  width: 250px;
  height: 250px;
  position: relative;
}
.hoverbase1 a br {
  display: none;
}
.hoverbase1 img {
  width: 250px;
  height: 250px;
  position: relative;
}
.hovertop1 {
  position: absolute;
  width: 250px;
  height: 250px;
  bottom: 0;
  left: 0;
  background-color: white;
  border: 2px solid black;
  opacity: 0;
  display: table-cell;
  vertical-align: middle;
}
.hoverbase1 a:hover + .hovertop1,
.hovertop1:hover {
  opacity: 1;
}
<div class='productList'>
  <div class='hoverbase1'>
    <a href='http://kingfisher.org.au/library-shelving'>
      <img src="http://kingfisher.org.au/pic/library_shelving.jpg" />
    </a>
    <div class='hovertop1'>
      <a href='http://kingfisher.org.au/library-shelving'>
        <h3>Library Shelving</h3>
      </a>
    </div>
  </div>
</div>

You can also view it on JSFiddle here.

Answer №1

I have created a demonstration using display: inline-block instead of table-cell, allowing for wrapping without unnecessary HTML markup.

Main CSS Attributes

  • The text is centered using a pseudo element called .product:before. This element vertically aligns the inline text in the middle. For compatibility with IE6 - 7, you can use a div instead.

  • The text inside .product has 0 opacity until it is hovered over.

  • The image uses position: absolute to position itself relative to its parent with position: relative, allowing it to be moved outside the normal flow for alignment purposes.

  • Transitions are applied to smoothen the opacity changes. A white border is initially set on .product which transitions to black when hovered over.

Note: There is currently no fallback for browsers that do not support opacity, like IE6 and IE7. To address this, you can use display: none in a conditional stylesheet for these browsers.

2 Example Scenarios

Click "Show code snippet" to run them.

No Need for an Unnecessary Div

The class .product is assigned to the <a> element, making the entire box a clickable link.

<a class="product" href="http://kingfisher.org.au/library-shelving">
  <img src="http://kingfisher.org.au/pic/library_shelving.jpg" />
  <h2>Library Shelving</h2> 
</a>

.product {
  width: 250px;
  height: 250px;
  display: inline-block;
  vertical-align: middle;
  position: relative;
  border: solid 1px #FFF;
  transition: border 1s;
  text-align: center;
}
.product:before {
  height: 100%;
  content: '';
  display: inline-block;
  vertical-align: middle;
}
.product img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  transition: opacity 0.5s;
}
.product:hover {
  border: solid 1px #000;
}
.product:hover img {
  opacity: 0;
}
.product h2 {
  opacity: 0;
  transition: opacity 0.5s;
  font-weight: none;
  display: inline;
  font-size: 1em;
}
.product:hover h2 {
  opacity: 1;
}
.product {
  text-decoration: none;
}
<a class="product" href="http://kingfisher.org.au/library-shelving">
  <img src="http://kingfisher.org.au/pic/library_shelving.jpg" />
  <h2>Library Shelving</h2>
</a>

Using a Div - Keeping Clicks Controlled

  • The class .product applies to a div containing both the image and text, where only the text functions as a link.

  • The <a> is given relative positioning to ensure it remains clickable, especially for IE8 and IE9.

  • The image is layered beneath the <a> by setting its z-index to 1.

<div class="product">
  <img src="http://kingfisher.org.au/pic/library_shelving.jpg" />
  <a href="http://kingfisher.org.au/library-shelving">
    Library Shelving
  </a>
</div>

.product {
  width: 250px;
  height: 250px;
  display: inline-block;
  vertical-align: top;
  position: relative;
  text-align: center;
  border: solid 1px #FFF;
  transition: border 1s;
}
.product:before {
  height: 100%;
  content: '';
  display: inline-block;
  vertical-align: middle;
}
.product img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  transition: opacity 0.5s;
  z-index: 1;
}
.product:hover {
  border: solid 1px #000;
}
.product:hover img {
  opacity: 0;
}
.product a {
  position: relative;
  text-decoration: none;
  font-weight: normal;
  opacity: 0;
  transition: opacity 0.5s;
  z-index: 2;
}
.product:hover a {
  opacity: 1;
}
a:hover {
  text-decoration: underline;
}
<div class="product">
  <img src="http://kingfisher.org.au/pic/library_shelving.jpg" />
  <a href="http://kingfisher.org.au/library-shelving">
    Library Shelving
  </a>
</div>

Answer №2

For optimal results, consider including the CSS property position:relative; in the parent div that houses your <h2> element. Then, apply the following styling to the <h2> tag:

position:absolute;
top: 50%;

Answer №3

When using the table-cell property, you can achieve vertical centering along with the standard horizontal centering provided by text-align:center.

.container1 a {
    display: table-cell;
    vertical-align: middle;
    text-align:center;
}

Give it a try.

Answer №4

Take a look at this simple solution I've come up with. The trick is to set the line-height on the parent element, and then adjust the vertical-align property on the child element (not the parent!). Remember that vertical-align only functions within one line of space. Even if you specify a height:300px; for a div, the default line-height will be determined by the font-size, so you'll need to define it manually.

Check out the code snippet here!


div{
    text-align:center;
    line-height:300px;
    border:1px solid black;
}

h1{
    vertical-align:middle;
}

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 way to implement <li> in place of <div> to ensure the tool-tip code functions properly?

To see an example, please refer to this fiddle: http://jsfiddle.net/66nLy/12/ I am looking to achieve a similar functionality on a webpage, but using <li> instead of <div>. Here is the HTML code snippet: <table class="base-table selection- ...

What methods can I use to adjust the selected option according to the value in the database?

To introduce you to my work, I have a table filled with data from a database that functions as a CRUD - Create, Read, Update, Delete table. Within this table, there is a column where EDIT and DELETE buttons are located. Clicking on the EDIT button trigger ...

Update the image on a webpage by simply clicking on the current image

Hey there, I'm looking to implement a feature where users can choose an image by clicking on the current image itself. Here's my code snippet. The variable url holds the default image. My goal is to make the current image clickable so that when ...

The div element is unable to activate the modal due to tabindex issues

Seeking Assistance with a Specific Scenario I have a specific layout where a div is enclosing an image. The desired functionality is that when the div is clicked with a mouse, a small tooltip modal should appear displaying address information. This can be ...

Errors persist with PHP form submission despite all fields being filled out

Snippet of PHP code for form validation: <html> <head> </head> <body bgcolor="000033" text="navy"> <?php $nume=""; $email=""; $subiect=""; if (!$nume || !$email || !$subiect) { ?> <h4 style="color:gray" align="center"> ...

Does IE 9 support Display Tag?

Although this may not be directly related to programming, I have been unable to locate any information regarding the compatibility of IE 9 or even 8 with the Display Tag Library. The documentation is silent on the matter. If anyone has encountered any cha ...

Comparing Strict CSS with Hacky CSS - Which is the Better Choice?

When working with CSS, it becomes evident fairly quickly that certain styles are not universally compatible across different browsers. For instance, achieving a semi-transparent PNG required a convoluted solution for Internet Explorer like: filter: pro ...

Solving the Issue of Assigning a Random Background Color to a Dynamically Created Button from a Selection of Colors

Trying to create my own personal website through Kirby CMS has been both challenging and rewarding. One of the features I'm working on is a navigation menu that dynamically adds buttons for new pages added to the site. What I really want is for each b ...

The overlay of the background image is excessively oversized

After implementing the following CSS to showcase a background image: height: 90%; /* or any other value, corresponding with the image you want 'watermarked' */ width: 90%; /* as above */ background-image: url('<?php echo "study/".$_SESS ...

MANDATORY activation of CONFIRMATION

Hello everyone, I'm seeking assistance with my code. Below is the form code I need help with: <form action="input.php" method="POST"> <input type="text" class="input" name="firstname" placeholder="First Name" required> <input t ...

What is the best way to center a menu for a cohesive and balanced appearance?

I am encountering an issue with my design. I am attempting to center-align a menu, but I want it to appear uniform and consistent. I want it to resemble the layout shown in the image link below. https://i.sstatic.net/D3Rep.png I cannot understand why my ...

Getting the input tag id of an HTML form can be achieved by using the "id

<?php $i = 1; $query1 = mysql_query("SELECT * FROM `alert_history` ORDER BY `alert_history`.`id` DESC LIMIT ".$start.",".$per_page.""); while($result = mysql_fetch_array($query1)){ echo '<td colspan = "2">& ...

"Utilizing Bootstrap's hamburger menu for a sleek solution when your menu becomes overcrowded

One interesting aspect of Bootstrap is its ability to collapse menu items into a hamburger menu within the navbar at specific window size breakpoints. However, there are instances where even on larger screens that exceed these breakpoints, the hamburger bu ...

Tips for properly positioning and rotating text in CSS and HTML!

My goal is to place a rotated headline next to some text, but I'm facing challenges with positioning when the page is resized. While absolute positioning works easily in a static scenario (left picture), it fails when the page size changes (right pict ...

Utilizing flexbox to create spacing between elements and ensuring there are no margins on the parent

Discover a Codesandbox demo at: https://codesandbox.io/embed/silly-firefly-87cov A unique challenge awaits with this project - elements within the parent container are positioned dynamically using flexbox. But how can we apply margins selectively only bet ...

col-md is taking precedence over col-sm at lower screen resolutions

Col-md takes precedence over col-sm in Bootstrap 4 https://i.sstatic.net/ydL5O.png ...

Changing the designated materialUI class

Within the project, I am utilizing this theme: export const theme = createMuiTheme({ ...defaultThemeConfig, overrides: { ...defaultThemeConfig.overrides, MuiListItem: { root: { '&:nth-child(odd)': { backgro ...

Centered div's overflow remains visible

Yes, the positioning of the parent container is set to relative. I am attempting to achieve a ripple effect by expanding multiple circles from a central point in all directions until they stretch beyond the viewport. I have created circular divs that are ...

PHP Random Background Image Selector

I have a PHP code that is currently displaying a random header image every time the page is refreshed. While this works fine, I now need to add specific background-position css properties to some of the images. For instance, I would like 'headerimage ...

Creating a Three by Three Grid with HTML and CSS

I have a total of 20 elements to display in a grid view. However, I specifically want a 3x3 grid view, where only 9 elements will be visible in the view window. The remaining elements should be placed on the right side of the window in a scrollable manner. ...