Arranging two elements in a div with distinct alignments

I have a variety of elements within a single div.

My goal is to align one element to the right and another element to the left within the same container.

Here's a look at the code snippet:

<div class="image_meaning" style="display: none; background-color: white; height: 35px; margin-left: 1px;">
    <input type="checkbox" id="points" value="Temporal Filter" style="text-align: left; "/>
    <label for="tempral_filter" style="text-align: left; ">Points</label>

    <img style="text-align: right;" src="{{ STATIC_URL }}img/cross.png"/>-abc
    <img style="text-align: right;" src="{{ STATIC_URL }}img/blue_triangle.png"/>-cde
</div>

Despite implementing this code, both elements end up aligning to the left. Any suggestions on how to achieve the desired alignment?

Answer №1

Answer

If you're facing a problem, there are several ways to solve it. The most common way back in 2016 was using the css float property. However, more modern approaches include using flexbox or grid.

Using flexbox

You can utilize display: flex for this purpose.

Flexbox is supported by newer browsers. Keep in mind that if you have users on IE (9 and below), this method might not be suitable.

Here's an example of html:

<div class="wrapper">
    <div class="block"></div>
    <div class="block"></div>
</div>

And the corresponding css:

.wrapper { display: flex; }
.block { width: 50%; }

View the live demo.

Utilizing grid

You may also opt for display: grid for achieving the desired layout.

Grid layout is mainly supported by the most modern browsers (as of Sep 2017). If your audience uses evergreen browsers, then go ahead with this option; otherwise, stick with flex.

Example html:

<div class="wrapper">
    <div class="block"></div>
    <div class="block"></div>
</div>

Sample css:

.wrapper {
  display: grid;
  grid-template-columns: 1fr 1fr;
}

Check out the live demo here.

Using float

The classic method involving the css float property has been used since ancient times and remains compatible with virtually all browsers. Just keep in mind the clearfix issue.

Example html:

<div class="wrapper">
    <div class="block-left"></div>
    <div class="block-right"></div>
</div>

Corresponding css:

.block-left { float: left; }
.block-right { float: right; }

If floated elements affect the parent's height, you can use the clearfix hack to address this issue.

To apply it:

.cf:before,
.cf:after {
  content: " ";
  display: table;
}

.cf:after { clear: both; }

Then on your parent element:

<div class="wrapper cf">

This will ensure that the parent accurately encompasses the floated elements' height.

Learn more about what the clearfix hack is.

Take a look at the demo here.


Other Approaches

Using inline-block

Another option would be employing the inline-block property to position elements alongside each other.

Note that dealing with white space in html between blocks can be tricky when using inline-block. You have the choice to remove the space, add a negative margin, or set the parent's font-size to 0 to counteract this issue.

Sample html:

<div class="wrapper">
    <div class="block"></div><div class="block"></div>
</div>

CSS code snippet:

.block { display: inline-block; }

/* Optional zero font for wrapper
   Then reset blocks to normal font-size */
.wrapper { font-size: 0; }
.block { font-size: 16px; }

/* Optional negative margin if you can't
   remove space manually in the html.
   Note that the number is per use case. */
.block { margin-left: -.25em; }

Try out the live demo.

Applying position: absolute

An alternative strategy is to absolutely position elements within a relative container. However, this method may pose challenges for responsive designs and similar layouts.

Sample html:

<div class="wrapper">
    <div class="block block-left"></div>
    <div class="block block-right"></div>
</div>

Sample css:

.wrapper { position: relative; }
.block { position: absolute; }

.block-left { left: 0; }
.block-right { right: 0; }

Explore the live demo.


Understanding Why Your Solution Fails

Your attempt with the text-align css property affects inline elements and text, but it does not shift elements like float does.

text-align influences the children of the applied element.

Answer №2

Replace text-align with float: left and float: right for alignment of elements.

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

Creating dynamic div elements using jQuery

I used a foreach loop in jQuery to create some divs. Everything seems to be working fine, but for some reason, my divs are missing SOME class properties. Here is the code snippet I am using: $("#item-container").append("<div class=\"panel col-md-2 ...

No matter how much I try, the text refuses to align with the top-left corner

I have been working on creating a loading screen, but I am facing an issue with aligning the h1 tag selected to the top left. As a young developer at the age of 13, I am quite confused. I attempted to use the following CSS properties: vertical-align: top; ...

One-click URL to trigger iPhone/iPad or Android app to open automatically in browser

Is there a specific way to create a link on an HTML page that will open an app on an iPhone, iPad, or Android device if the app is installed? I have found methods for call links and launching apps via iTunes, but is there a standard format for these types ...

A guide to customizing nested elements in react using styled-components

Currently, I am utilizing styled components to apply styles to a child element inside a div using nested css. For a demonstration, you can view my example here const customStyles = theme => ({ root: { ...theme.typography.button, background ...

Activating/diverting DIV elements through specific functions (on a WordPress website)

I have a stronger background in HTML and CSS, but I'm struggling with coding the functionality I want to see on a WordPress page. My goal is to create a page that displays upcoming events for a specific province or region of Canada, with an interactiv ...

Modifying the CSS based on the SQL data retrieved

I'm currently diving into the world of php and jquery, attempting to build a webpage that displays player information and their status fetched from my Mysql server. Although the core code is functional, it's a mashup of snippets gathered from va ...

Accessing JavaScript results in PHP

Hello everyone! I am working on creating a dropdown menu for selecting time using JavaScript to get the computer's current time. My goal is to have an output that automatically selects the option in the dropdown if it matches the computer's time. ...

Navigating with AngularJS

My server is utilizing angular for routing purposes. It sends a HTML file containing a js file with routing using angular js to the browser. Here is the server code (which sends the check.html with the routing file main.js) : var express = require("expre ...

Creating a jQuery multiple image preview feature is a simple and effective way to

Looking to implement a single image upload preview function in jQuery? Want to modify it to allow for multiple image uploads with separate boxes? Check out the HTML script below. <!DOCTYPE html> <html> <head> <title></title> ...

Could Google Adsense be causing issues with my website's navigation bar?

There seems to be an irritating bug that I've come across. While navigating my website, [the menu (located in the top right corner) functions correctly]. However, when you land on a page with a Google AdSense ad, the menu suddenly appears distorted ...

Is there a way to alter the text color using JavaScript on the client side?

Is there a way to change the color of a list item in a ul based on whether it is a palindrome or not? Here is the JavaScript file I am working with: function isPalindrome(text){ return text == text.split('').reverse().join(''); } c ...

Trigger the datepicker to open by clicking anywhere within the TextField in MUI

I am trying to enhance my date picker functionality by displaying it when users click anywhere within the field, not just on the calendar icon. Below is the picker: https://i.stack.imgur.com/mrAui.png export function DatePickerField(props) { ...... ...

Accessing video durations in Angular 2

Can anyone help me with retrieving the video duration from a list of videos displayed in a table? I attempted to access it using @ViewChildren and succeeded until encountering one obstacle. Although I was able to obtain the query list, when attempting to a ...

Is it possible to toggle all parent targets in Bootstrap?

When trying to showcase my point, I believe it is best demonstrated by visiting Bootstrap documentation at https://getbootstrap.com/docs/4.0/components/collapse/ and viewing the "multiple targets section." In this section, you will find three buttons: togg ...

When I print a specific A4 format division containing content as a pdf, I noticed that there is excess white space above the content on the second and third pages. I am curious

Feeling a bit frustrated here, I've tried everything but my project seems to break whenever I try to print 3 pages as a PDF and enter the printing dialog. If you'd like to check out the pages directly, click this link. Pressing cmd shift P will ...

Maintaining the order of elements in Angular's insertion process

I am currently facing an issue with my HTML fragment that iterates over a key and value collection. Everything works perfectly when I insert values into an object and iterate through it using the HTML fragment. However, in order to maintain a specific key ...

I have noticed that there are 3 images following the same logical sequence, however only the first 2 images seem to be functioning correctly. Can you help

Update: I have found a solution that works. You can check it out here: https://codepen.io/kristianBan/pen/RwNdRMO I have a scenario with 3 images where clicking on one should give it a red outline while removing any outline from the other two. The first t ...

Toggling designs with a simple click

I'm currently working on a ReactJS project and I'm trying to figure out how to change the color of a button when it's clicked. I've heard about the Ripple API, but I find it quite complex to use. Can anyone offer some advice on how I ca ...

What is the best way to handle JSON data from an HTTP request using Vue and an HTML script?

Looking for guidance on how to process the json data from this link to display attributes such as latitude, longitude, speed, etc. using vue and html? Json-content: { "64dda53cc503629cedb5f8c8102708ed": { "Test": { "lat": 50, "lon": 10 ...

Incorporate dynamic animations into text wrapping using React

Currently, I am in the process of learning React and have successfully created a flexbox with 6 child containers using the wrap property. Now, I am looking to add animation when the containers wrap onto a new line. I attempted to add a transition animatio ...