align image vertically within a floated container

There are 5 floated divs with heights stretched to 100% of the document height using JavaScript. Each of the 5 divs contains an img element.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link type="text/css" rel="stylesheet" href="style.css"/>
</head>
<body>
    <div id="wrapper">
        <div id="static"><img src="http://www.rs.dhamma.org/wheel.gif"/></div>
        <div><img src="http://www.rs.dhamma.org/wheel.gif"/></div>
        <div><img src="http://www.rs.dhamma.org/wheel.gif"/></div>
        <div><img src="http://www.rs.dhamma.org/wheel.gif"/></div>
        <div class="clear"><img src="http://www.rs.dhamma.org/wheel.gif"/></div>
    </div>
</body>
</html>​

Javascript:

// Adjusts columns height to fit 100% of the document;
function adjustColumnHeight(){
        var docHeight = $(document).height();
        $("#wrapper div").height(docHeight);
};

$(document).ready(function(){
    adjustColumnHeight();
    });

and CSS:

*{
    margin: 0;
    padding: 0;    
    }

#wrapper{
 width: 1000px;
 margin: 0 auto;    
    }

    #wrapper div{    
        padding: 0 20px;
        background-color: #9F81F7;        
        float: left;
        border-right: 1px solid black;
    }
    #wrapper img{

    }

div.clear:after{
    content: " ";
    clear: both;
    }

​Tried setting the parent div to display: table and the img to

display: table-cell, vertical-align: middle
but without success. Setting margin-top: 50% didn't yield the expected results.

JSFIDDLE LINK HERE!!!

Any assistance would be greatly appreciated.
Thank you!

Answer №1

To perfectly position images, consider using absolute positioning with top: 50% and margin-top: -63px. This method works well when the image height is fixed at 126px. If the image sizes vary, you can dynamically set the margin-top using JavaScript after the images have loaded.

For a demonstration of the static positioning method, check out this link: http://jsfiddle.net/3gqcS/2/

Answer №2

It may seem unconventional, but one way to achieve this is by adjusting the line-height of the div to match the combined height of the div and the image, then using overflow:hidden to contain it.

<div id="static" style="height: 481px; line-height: 607px; overflow: hidden;">

Answer №3

If you're utilizing JavaScript and jQuery (can't do without it), there's a way to achieve...

Take a look at this: http://jsfiddle.net/828pW/

Below is the actual code snippet:

function verticallyCenterImage(img)
{
    if(img.height)
    {

        $(img).css({
            position:'absolute',
            top: ($(img).parent().height() - img.height)/2
        }).parent().css('position', 'relative');

    }
    else 
    {
        setTimeout(function(){

            verticalAlignImage(img);
        }, 100);
    }
}

Answer №4

Here is a suggestion for centering your images:

    Set the columns with:
    position:relative;
    width:<width>;/* width must be set */

Then, adjust the images with:

    position:absolute;
    top:0;
    bottom:0;
    margin:auto 0;

Following these steps should center the images perfectly but keep in mind that you may need to set the column width as images with absolute positioning do not take up any space.

Instead of using javascript, you can simply add:

    html, body, #wrapper, #wrapper div{height:100%;}

as an alternative solution.

Source:

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

Error: Collection2 validation did not pass: The field 'name' must be filled in, the field 'email' cannot be empty, and the field 'message' is mandatory

I need to set up a way for visitors to send messages through my website const mongoose = require("mongoose"); mongoose.connect("MongoDb-Connection-Uri") .then(() => { console.log("mongodb connected"); }) .catch(() => { console.log("fail ...

"Converting a basic function into a promise for an AngularJS tutorial: How to handle the error message '

To help my colleagues understand AngularJS, I am creating a dummy exercise. In this example, I want to call a service that provides an Object Array to be passed into a Controller and assigned to a $scope variable (using information about the Beatles). Inst ...

The error message "404 Not found" is returned when attempting to retrieve a Google spreadsheet

I have exhausted all of my options on the web trying to retrieve my Google spreadsheet as a json file. $.getJSON() However, I am constantly receiving a 404 Not Found error. When I publish to the web, the URL I get is: https://docs.google.com/spreadsheets ...

"Enhance Your Website Navigation with Bootstrap Navbar Links Extensions

I'm stuck on nesting a "navbar" in a Bootstrap row. The issue I'm facing is how to get the links to expand across the entire column. https://i.sstatic.net/9QbSN.png The code for this problem looks like: <div class="col-6 p-3 ...

Using React Native to iterate over a multidimensional array with the array map function

I want to iterate through a two-dimensional array like the one below: var array=[["1"],["3","8"],["4","8","3"],["4","8","3","9"],["1","8","3","9","2"],["6","8","3","9","2","1"],["4","8","3","9","2","11","2"]] Currently, this code only loops through the & ...

Retrieving results from a Node.js application that utilizes multithreading

A new function called diversify() has been developed to execute an expensive function f() in parallel on all the cores of the machine in which it is being deployed. Additionally, a mechanism has been implemented so that when f() returns a value on one core ...

Modify parent component state when input in child component changes in React

I am working on a parent component called NewPetForm: class NewPetForm extends React.Component { state = { name: '', age: '', animal: '', breed: '' }; render() { ...

Ways to identify when the scroll bar reaches the end of the modal dialog box

I have been working on a modal that should display an alert when the scrollbar reaches the bottom. Despite my efforts to research a solution, I am struggling to detect this specific event within the modal. The desired outcome is for an alert to pop up once ...

Harnessing JavaScript templates within PHPHow to integrate JavaScript templates

I am currently working on a PHP document where I incorporate 'chapters' (jQuery tabs) in two different ways: Whenever a new chapter is generated, it gets added to the list as well as to the database using JavaScript and Ajax. I have already i ...

Mistakenly appearing at the top of the window instead of the bottom of the window

Utilizing Vue.js to fetch resources from a Laravel API periodically and paginate(), after retrieving the initial 10 instances, I aim to get the next 10. Here's how my method looks: scroll () { window.onscroll = () => { let bottomOf ...

Passing data from the server to the HTML page for manipulation

I need assistance in retrieving and manipulating the value stored in the variable $result[] from a PHP file to my HTML file for further processing. Can you provide guidance or reference code on how to return data from server side to client side? Here is a ...

Exploring Node and Express Request Query

I'm struggling with a specific endpoint setup in my code. // GET /api/logs/ app.get('/api/logs', function (req, res) { if (req.query.reverse === true) { res.send((mainModule.logs).reverse()); } else { res.send(mainModule.logs) ...

Choose either immediate offspring or immediate offspring of immediate offspring

I am struggling to create a CSS Selector that follows DRY principles. The selector needs to target elements within a group but not those within a subgroup of the main group. Elements should only be direct children of the main group or wrapped in an addit ...

The margin-left and margin-right in HTML CSS are not cooperating to center a div

I'm currently diving into the world of CSS and HTML, but I've hit a roadblock. The margin-left and margin-right in the ".logo" div class are refusing to center the div as expected. Despite conducting research and meticulously checking over the co ...

Adjust alterations in a Vue Component to apply to separate routes

I have a Filter tab component that I use in various routes. When I click on a tab, it becomes active. After clicking on one tab, I want it to remain active in other routes as well. How can I achieve this? Any suggestions or articles would be greatly apprec ...

Selecting radio buttons using Bootstrap and JavaScript

I'm interested in incorporating this bootstrap radio selection feature into my JavaScript code. For example, if option1 is true, I want to execute a specific action... How can I achieve this? <div class="alert alert-info" role="alert"> < ...

Having trouble rendering the React app; encountered an error: JSX contents are unterminated

I am currently facing an issue while trying to fetch data from an API in React using Axios. How can I ensure that useEffect functions properly? My objective is to create a page by fetching data from an API in React through Axios. I have designed a compon ...

Encountering a client component error with the app router in Next.js version 13.4.9

Encountering an error in Nextjs that persists until the 'use client' directive is removed. Warning: Rendering <Context.Consumer.Consumer> is not supported and will be removed in a future major release. Did you mean to render <Context.Con ...

The process of registering with JWT tokens and the challenge that arises when a token expires

I had the idea to implement a registration process that requires users to provide their username, email (which must not already exist in the database), password, and confirm password. The project is built using NextJS with pages router and Typescript. impo ...

CSS grid tracks remain fixed in size while other tracks expand

Why won't the grid track cells dynamically shrink when other cells are enlarged in the following code? In this snippet, hovering over any track section causes that cell to grow to 75% of the viewpoint. However, instead of the other sections shrinking ...