Aligning a div vertically in the center of its parent container

I am trying to vertically align a child element within its parent element

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style type="text/css">
#body {
font-family: sans-serif, arial, 'Roboto';
}
#outer {
width: 280px;
background-color: white;
height: 253px;
background-color: #f0f0f0;
}
.imgbox {
height: 174px;
width: 270px;
overflow: hidden;
display: table;
margin: 0 auto;
background-color: black;
text-align: center;
}
.img_content {
max-height: 174px;
max-width: 270px;
margin: 0 auto; 
vertical-align: middle;
display: table-cell;
}
.titlebox {
max-width: 270px;
text-align: center;
}
.title {
font-weight: 900;
font-size: 14px;
}
</style>
</head>
<body>
<div id="outer">
<div class="imgbox">
<img class="img_content" src="http://lorempixel.com/700/100" alt="test image">
</div>
<div class="titlebox">
<p class="title">Lorem ipsum Lorem</p>
</div>
</div>
</body>
</html>

Can anyone explain why the img_content class doesn't vertically align in the middle of the imgbox class when the image exceeds the width?

Answer №1

Here is the custom CSS code to style image containers:

.container {
   height: 200px;
   width: 300px;
   overflow: hidden;
   margin: 0 auto;
   background-color: #f2f2f2;
   text-align: center;
   position: relative;
 } 

.image {
   max-height: 200px;
   max-width: 300px;
   position: absolute;
   transform: translate(-50%,-50%);
   top: 50%;
   left: 50%;
 }

Answer №2

Utilize css3 flexbox. The following css code should be included on the parent element.

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

#body {
  font-family: sans-serif, arial, 'Roboto';
}
#outer {
  width: 280px;
  background-color: white;
  height: 253px;
  background-color: #f0f0f0;
}
.imgbox {
  justify-content: center;
  align-items: center;
  display: flex;
  height: 174px;
  width: 270px;
  overflow: hidden;
  margin: 0 auto;
  background-color: black;
  text-align: center;
}
.img_content {
  max-height: 174px;
  max-width: 270px;
}
.titlebox {
  max-width: 270px;
  text-align: center;
}
.title {
  font-weight: 900;
  font-size: 14px;
}
<div id="outer">
  <div class="imgbox">
    <img class="img_content" src="http://lorempixel.com/700/100" alt="coba">
  </div>
  <div class="titlebox">
    <p class="title">Lorem ipsum Amet</p>
  </div>
</div>

Answer №3

There are multiple ways to achieve this effect. One option is to enclose the img tag within a div with a class called "wrapper". The wrapper div can then be styled like this:

.wrapper {
       vertical-align: middle;
       display: table-cell;
}

You can then remove the display:table-cell and vertical-align:middle properties from the image itself.

If you prefer not to make changes to existing CSS, you can explore another approach in this working fiddle: https://jsfiddle.net/mfkxq728/

Alternatively, you could utilize either flexbox (although browser support may vary) or the traditional relative-absolute positioning technique with a translate-Y property. The latter method may require browser prefixes for consistent performance.

Happy coding!

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

When trying to click the button in Navbar.jsx, I encounter an error when attempting to invoke the setShowCart(true) function

I've encountered an issue while trying to call the setShowCart(true) function in Navbar.jsx. I'm unsure of how to fix this. import React from 'react' import Link from 'next/link'; import {AiOutlineShopping} from 'react-ic ...

Error: Unable to register both views with identical name RNDateTimePicker due to Invariant Violation

Encountering an issue while attempting to import: import DropDownPicker from 'react-native-dropdown-picker'; import DateTimePicker from '@react-native-community/datetimepicker'; <DropDownPicker zIndex={5000} ...

Place the division at the bottom of the screen

I'm facing an issue where I am trying to place a div at the bottom of the viewport but it's not working as expected. Here is how my current setup looks like: html <div class="parent"> <div class="bottom"> </div> </div&g ...

Update the section tag upon submission using jQuery on a jQuery Mobile HTML page

I have integrated a jquerymobile template into Dreamweaver 6.0 to create a mobile app interface. The home screen features four buttons - specifically, View, Create, Update, Delete. Upon clicking the Create button, a new screen is opened (each screen corres ...

React and Redux encounter an issue where selecting a Select option only works on the second attempt, not the first

I am currently working on a React/Redux CRUD form that can be found here. ISSUE RESOLVED: I have encountered an issue where the state should be updated by Redux after making an API call instead of using this.setState. The concept is simple: when a user s ...

Sending an array of objects in JavaScript to a controller

I have a dynamic form that I'm trying to submit to my Controller. Instead of sending just a string or an array with data, I need to pass an array of objects using ajax request after building the Javascript Array. The challenge is that when I send only ...

The image appears to be overlapping within the navigation bar

I'm having trouble understanding why the image is overlapping on this website. The image is enclosed in a link tag, and upon inspecting it, the link tag seems to be correctly positioned while the image appears slightly below. I can't seem to ide ...

"Displaying 'Object Object' as a title when hovering over an element

I am currently using an accordion element to display several FAQs on a webpage. The code snippet for the accordion with content is as follows: { Object.keys(FAQS).map((key, index) => { return ( <div key={key}> ...

What is the process of caching images when they are loaded through a php script?

My PHP script acts as a random image generator by querying the database for user images and returning a random one. Below is the code snippet responsible for serving the randomly chosen image. header('Content-Transfer-Encoding: binary'); header( ...

Adjust image size with react - personalize styling for react-easy-crop

I am currently working on developing a basic react component that involves cropping images using react-easy-crop. It seems like the style of the react-easy-crop module can be customized with the style prop, which consists of three objects: containerStyle, ...

Keep the final item in an array that shares the same attribute

I am working with an array const obj=[{fullCart: 5, halfCart: 4, smu: 3, stowage: 5, index: "FC-093"}, {fullCart: 5, halfCart: 4, smu: 8, stowage: 5, index: "FC-093"}, {fullCart: 5, halfCart: 4, smu: 0, stowage: 5, index: "FC-093 ...

What is the best way to make a div pull its background image directly from the internet instead of using the cached version?

Running relevant Javascript every fifteen minutes to fetch the appropriate image from the internet: document.getElementById('weatherbug').style.background = "url('http://tinyurl.com/jwltx5s') repeat scroll -1px -24px transparent"; The ...

Receiving a 401 error when making an Axios post request

Having trouble with a 401 error when making a POST request to an API? Don't worry, I've got some suggestions that might help. I'm able to successfully make GET requests to the same API with a 200 status, so it could be a syntax issue in the ...

Is there a way to prevent an item from being selected in a Select component when the first letter of the option is pressed?

I'm currently working with the material UI Select component and I'm attempting to create a filter within it that will only display items matching the user's input. Below is a simplified example of my current project: function App() { con ...

The map displayed on google.com appears different from the one featured on our website

The integration of the JS for the Google map on our website is working smoothly without any issues. However, when I zoom into our address on google.com/maps, our Hotel is listed as "Hotel". On the map displayed on our website, there are only a few entries ...

What is the best way to center align my horizontal subnav?

I am currently working on a horizontal navbar with horizontal submenus. One issue I am facing is getting the elements in mysubnav to align centrally instead of being pushed to the left all the time. If you need a visual representation of what I mean, plea ...

Vue.js - I am looking to create dynamic buttons that change color when clicked

I have dynamically created buttons using v-for and now I want the clicked button to change color while the others remain the same. <template> <div id="exam-screen" class="exam jumbotron"> <h1>{{ title }}</h1> <div cl ...

Creating two interactive animations utilizing a combination of CSS and Javascript, triggered by the click event on

Looking to incorporate two unique CSS animations into my project. Utilizing two buttons and one object, I want the first animation to trigger upon clicking the first button. I understand how to handle one button and one animation, but am unsure how to man ...

What is the best way to extract data from an array of objects in a JSON response?

I am currently exploring the utilization of API's in React. Right now, I am developing a search input feature for country names using the Rest Countries API. The data is being pulled from . However, I am facing a challenge in handling this data as it ...

Obtaining the attribute value of a disabled element in an Angular JS application

Currently, I am struggling to retrieve the attribute value of a disabled element during runtime and then assert its value. The code I'm using is not providing the desired result: softAssert.assertFalse(shrSub.nextButton().waitForPresent().getAttribu ...