Tips for aligning an element vertically when it has a float using CSS or JavaScript

I am struggling with centering the image within the article list loop I created. The code snippet looks like this:

  <article class="article <?php if($i%2==0) { echo 'even'; } else { echo 'odd'; } ?>">
    <section class="container">
      <section class="content">

        <h2><?= $r['title'] ?></h2>
        <span class="subtitle"><?= $r['subtitle'] ?>&nbsp;</span>

        <section class="text">
          <?= $r['text'] ?>
        </section>

      </section>


      <section class="image">
        <img src="<?= $img ?>" alt="<?= $img ?>" class="img-responsive article-image" />
      </section>
    </section>
  </article>

I have been attempting to use jQuery to vertically center the image in relation to the content at all times. Specifically, I wanted to achieve an image margin-top that is calculated as

(content.height()-image.height())/2
.

Despite my efforts, the jQuery approach using

$('.image').closest($('.content'))
did not yield the desired result. It kept selecting the first .content element and adjusting the margin-top based on that.

If you have a solution utilizing either jQuery or CSS to accomplish this alignment issue, I would greatly appreciate your guidance. Previous attempts using CSS were unsuccessful due to float properties applied to both the image and content elements, causing them to be positioned horizontally next to each other.

EDIT: http://jsfiddle.net/hwx5Lsvz/

Answer №1

It is not possible to change the float behavior based on the specifications.

A floating box should be positioned as high as possible.

However, you can eliminate the float property and instead use

.content, .image {
    display: table-cell;
    vertical-align: middle;
}

.container {
  width: 90%;
  max-width: 1200px;
}
.img-responsive {
  width: 100%;
  height: auto;
}
#list_articles {
  float: left;
  width: 100%;
}
#list_articles .article {
  float: left;
  width: 100%;
  font-size: 18px;
  color: #555;
  line-height: 25px;
  padding: 80px 0;
  position: relative;
}
#list_articles .even {
  background: #fff;
}
#list_articles .odd {
  background: transparent;
}
#list_articles .article .content {
  width: 50%;
  padding-right: 10%;
}
#list_articles .article .image {
  width: 40%;
}
#list_articles .article h2 {
  color: #184180;
  font-size: 30px;
  font-weight: 700;
  float: left;
  width: 100%;
  padding: 0;
  margin: 5px 0 10px 0;
}
#list_articles .article .subtitle {
  color: #5271a0;
  float: left;
  margin-bottom: 45px;
  width: 100%;
  font-weight: 300;
}
#list_articles .article .text {
  float: left;
  width: 100%;
  font-weight: 300;
}
.content,
.image {
  display: table-cell;
  vertical-align: middle;
}
<section id="list_articles">
  <article class="article">
    <section class="container">
      <section class="content">
        <h2>Here's a title</h2>
        <span class="subtitle">Here's a subtitle &nbsp;</span>
        <section class="text">
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum consequat consequat nunc, vel pellentesque elit maximus non. Aliquam eu interdum purus. Suspendisse venenatis finibus sem in ornare. Cras volutpat aliquam tincidunt. Sed massa tortor, consectetur id nulla auctor, porttitor mattis mi. Cras feugiat augue eget urna fermentum, nec venenatis tellus auctor. In pretium consectetur purus, id finibus diam tincidunt eget. Donec nec tincidunt ante. Donec elementum tincidunt faucibus. Aliquam volutpat nibh ornare enim sagittis efficitur. Maecenas convallis consectetur nulla quis ultrices. Nam dolor justo, vehicula a laoreet at, tincidunt eu lacus. Fusce hendrerit velit a convallis dictum. Etiam dignissim, odio at fringilla aliquam, libero dui hendrerit tortor, eu blandit lectus leo ut nulla.
        </section>
      </section>
      <section class="image">
        <img src="http://images.visitcanberra.com.au/images/canberra_hero_image.jpg" class="img-responsive article-image" />
      </section>
    </section>
  </article>
</section>

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

Connecting Next.js to a Database: A Step-by-Step Guide

I am interested in developing an application similar to Samsung Health that will involve heavy querying on a database. I am unsure whether it would be more beneficial to create a custom server using Node.js (with Express.js) instead of using the integrate ...

Display thumbnail images in jquery-ui dropdown menu

Hello, I'm looking to display a small image (the user's thumbnail) on the jquery-ui dropdown by making an ajax call. As someone new to ajax and unfamiliar with jquery-ui, I would appreciate some guidance in the right direction. Thank you! HTML/J ...

Issue encountered while transferring data using Ajax

I am a novice in the realm of ajax and currently immersed in a project that demands passing data from an ajax function to a php page for the purpose of dynamically generating and displaying modals. Although I am successful in creating the modal, I suspect ...

Unable to precisely reach the very bottom of the scrollbar

When trying to move to the bottom of the scrollbar, I seem to reach a bit higher than the actual bottom. https://i.stack.imgur.com/Vt83t.png Here is my code: ws.onmessage = function (event) { var log = document.getElementById('log') ...

Spin a Material UI LinearProgress

I'm attempting to create a graph chart using Material UI with the LinearProgress component and adding some custom styling. My goal is to rotate it by 90deg. const BorderLinearProgressBottom = withStyles((theme) => ({ root: { height: 50, b ...

Attempting to create a JavaScript class within an HTML document

Having an issue with instantiating a JavaScript class in a separate HTML file. The JavaScript class looks like this: class Puzzle { constructor(fenStart, pgnEnd) { this.fenStart = fenStart; this.pgnEnd = pgnEnd; } } module.exports = Puzzle; ...

Child object in Three.js does not inherit transformation from its parent

Consider a scenario where there is a main object with multiple child objects in a given scene. Update: Here is the code snippet for creating a mesh (assuming the scene and camera are already set up). Code snippet for creating the parent group: var geome ...

Fetching data from the database and seamlessly displaying it in a single view with the help of jQuery within the ASP.NET MVC framework

Currently, I am working with asp.net MVC to develop an application. In this project, I have a view that requires a treeview in the left pane and the details of the selected node item to be displayed in the right pane. The left pane's table represents ...

Concealing divisions on a website with CSS styling

In my div, I have some text that I want to hide. <div style='visibility:hidden;' id='emailid'>$email</div> Although the visibility attribute successfully hides the text, it leaves behind empty space on the webpage where th ...

Adding metadata fields to an existing Markdown file within TinaCMS

Is it feasible to enhance a Markdown file using TinaCMS by introducing new frontmatter fields? Instead of generating a brand new Markdown file, my goal is to modify the current one by appending new frontmatter fields. Currently, I am able to modify a sin ...

Is there a way to avoid getting a 404 error in Express when using multiple static directories?

I am working on serving files from two different folders to keep my admin and client content separate. The code I have set up initiates the two folders, but when Express looks for a file like example.css, it first checks the /static directory. If it doesn ...

Combining ajax and jsp to fetch data for a servlet

In my JSP file, I have two text fields - signUp and post. I want the post text to be sent to a servlet using AJAX function while the signUp text should be sent in the usual way through request.getParameter(). Can these two functionalities be combined with ...

What is the best way to display values from a Localstorage array in a tabular format using a looping structure

I have set up a local storage key 'fsubs' to store form submissions as an array. Here is how I am doing it: var fsubs = JSON.parse(localStorage.getItem('fsubs') || "[]"); var fcodes = {"barcodeno" : this.form.value.barcode, "reelno" : ...

Create an HTML and CSS code that allows you to split paragraph text into columns within a

I am seeking a way to create dynamic paragraph column text using only the Here is an example of how it could be displayed in HTML: <div> <p> Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantiu ...

Troubleshooting problems with dates in jQuery AJAX

Hey, I recently worked on formatting dates in jQuery Ajax. After fetching a date value from the database, I converted it to the format dd-MM-YYYY. However, there seems to be an issue where I'm receiving the previous month. For example, if the database ...

Is setting cache: 'no-store' in a fetch request enough to mimic client-side rendering behavior in Next.js?

Currently, I am working with Next.js and utilizing the fetch method to retrieve data: const res = await fetch(`${process.env.url}/test`, { cache: 'no-store', }) My understanding is that specifying cache: 'no-store' will trigger a fre ...

Guide to positioning a top navigation menu with dropdown items in the center using CSS: absolute positioning

I have implemented a pure CSS menu from this source on my website. It functions properly in the 'hamburger menu' mode, but I am encountering difficulties when attempting to center or right-align the menu in other modes. Despite trying various so ...

Challenges with Validating Bootstrap Datepicker Functionality

I need to restrict the datepicker input control to only allow selection of dates from the current date onwards. Despite trying to implement validation using the bootstrap-datepicker library and the following JavaScript code, I am still facing issues: $(& ...

Difficulty in arranging DIVs on a flat surface

As a user running Win XP with Firefox, IE, and Google Chrome browsers, I'm encountering an issue where I can't seem to align two DIVs on the same horizontal plane. My goal is to have the left div occupy 24% of the screen width while the right div ...

Exploring the Benefits of Using JSON in AJAX Requests

Can you help me determine the best way to extract data from a php page using ajax in the form of a json array? Here is an example code snippet: $.ajax({ type: "get", url: "assets/update_cart_user_fstore.php", data: up, cache: false, su ...