What is the best way to eliminate vertical spacing among li elements in CSS

I am facing a challenge with my HTML code and styling, which is just an example:

<div id="mn" style="margin-top:200px;">
                <div class="first">1</div>
                <div class="second">2</div>
                <div class="third">3</div>
                <div class="fourth">4</div>
            </div>

<style type="text/css">
        #mn, #mn div { display:inline-block; vertical-align:middle; }
        #mn div { width:350px; margin:5px; /* float:left Comment */ }
        div.first { height:5px; background-color:Red; }
        div.second { height:120px; background-color:#999 }
        div.third { height:50px; background-color:Yellow }
        div.fourth { height:180px; background-color:#ccc }
    </style>

The issue at hand is that the elements on the left side (the yellow and red ones) have excessive spacing between them. I aim to eliminate this large margin or spacing and maintain a consistent 5px margin for all elements.

In an attempt to address this, I devised a JQuery script to rearrange the list into divisions as follows:

<div id="mn_left"></div>
            <div id="mn_right"></div>
            <div id="mn" style="margin-top:200px;">
                <div class="first">1</div>
                <div class="second">2</div>
                <div class="third">3</div>
                <div class="fourth">4</div>
            </div>

$(document).ready(function () {            
            $("div", "#mn").each(function (e, value) {
                if ($("#mn_left").height() <= $("#mn_right").height()) {
                    $("#mn_left").append(value.outerHTML);
                }
                else {
                    $("#mn_right").append(value.outerHTML);
                }
            });
        });

While the script does the job effectively, I seek a solution that doesn't involve scripts.

Edit... I made an error by swapping li tags for divs, but the concept remains the same. The HTML now appears like this:

My ultimate goal is represented in the following image:

Answer №1

To begin, let me present your code in a more organized manner using list markup, as you mentioned it is a list:

HTML:

<ul id="mn">
    <li class="first">1</li>
    <li class="second">2</li>
    <li class="third">3</li>
    <li class="fourth">4</li>
</ul>

CSS:

#mn {padding:0; margin:0;}
#mn, #mn li { display:inline-block; vertical-align:middle; }
#mn li { width:350px; margin:5px; }
li.first { height:5px; background-color:Red; }
li.second { height:120px; background-color:#999 }
li.third { height:50px; background-color:Yellow }
li.fourth { height:180px; background-color:#ccc }

Next, eliminate the margin from #mn li:

#mn li { width:350px; /* margin:5px; */ }

You will notice that the list items are now aligned perfectly, except for the first one where the line height exceeds the item height. To rectify this issue, apply an overflow:hidden; to the list items and change the display property from inline-block to just block.

#mn, #mn li { display:block; vertical-align:middle; }
#mn li { width:350px; overflow: hidden;}

This should address all concerns, unless there has been any misunderstanding on my part.

Answer №2

After gaining clarity on your objectives...

To organize the second column, consider establishing a specific class for its items:

#mn .col2 { position: absolute; left: 355px; top:0; margin-top: 0;}

View Example on JSFiddle. (By the way, ensure you have #mn{position:relative;} in place for the code above to function correctly.)

An issue may arise if there are multiple items in the second column as each subsequent item will require a unique top position to maintain alignment.

In situations like these, it might be more efficient to incorporate Javascript instead of relying solely on CSS. This suggestion arises even from someone who usually advocates for maximizing CSS usage whenever possible!

Answer №3

What do you think of this approach? Instead of absolute positioning, we are using floats.

#mn {width: 720px;}
#mn div { width:350px; float:left; margin:5px; }
#mn div.second {float:right;}
div.first { height:5px; background-color:Red; }
div.second { height:120px; background-color:#999; }
div.third { height:50px; background-color:Yellow }
div.fourth { height:180px; background-color:#ccc }
  • All elements floated to the left.
  • A new CSS rule was added for the containing div with an ID of #mn. The width is calculated as the sum of each child div's width and margins, resulting in a total width of 720px.
  • New CSS declaration for the second div was introduced.

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

How to center an image vertically inside a link using CSS

My goal is to vertically align an image inside an anchor element using the following code: <ul class="thumbnails"> <li class="span2"> <a href="#" class="thumbnail"> <img src="http://www.forodefotos.com/attachme ...

Could the conflicting interaction between CSS transformation and animation be resolved by adjusting the order of the HTML elements

Hey there! I'm facing an interesting challenge with my menu design. The menu has rounded ends and diagonal spaces created using CSS transform skewx. Additionally, I have an animated element on the page. The issue arises when the animated element is p ...

The align-self-center property in Twitter Bootstrap Flex does not properly center elements vertically

I recently started working with twitter bootstrap 4.4.1 and flex to create a unique layout for my project. My main goal is to have a navbar at the top and the content displayed in the middle of the screen, as shown in the image here: https://i.sstatic.net ...

My custom CSS in React is being overshadowed by the default Bootstrap styles

View project image Currently working on a React project that requires Bootstrap. However, I am facing issues with Bootstrap overriding my custom CSS. Some default Bootstrap styles are affecting my headings. I have attempted various solutions such as placi ...

Is it possible to have 3 divs with the height of the tallest

I have a unique template that I employ for crafting responsive websites. It relies on boxes with percentage widths, floats, and clears. A prime instance can be viewed via this link. Notice how the three boxes vary in height. While it's simple to set a ...

Step-by-step tutorial on designing an input slider to dynamically adjust the CSS :before linear-gradient values

Is there a way to achieve a gradient effect using pseudo-element :before on an image that can be customized by adjusting a slider input? I've been trying to implement this feature with the following code, but have not been successful so far. var ...

The function .click() fails to execute upon page load, yet it functions successfully when utilized in the console

This is the code I am using: <script> document.getElementById("test").click(); </script> When I try to trigger the click(); function on page load, it doesn't work. However, when I execute it in the console on Firefox, it works ...

Issue with Modal Box: Datepicker not Displaying Correctly

I have implemented a modal box in my webpage. When I click on a text field where a datepicker is added, it does not display anything. However, when inspecting the element using Chrome's developer tools, I can see that the 'hasDatepicker' cla ...

Is there a way to achieve the same zooming and panning effects on an element using CSS transform instead of jQuery's

If you click on the following link, you will see a jsFiddle that I have created to demonstrate my question: http://jsfiddle.net/VbCcA/3/ In my project, I have developed a function that allows for panning and zooming to a specific element. This function i ...

The submit button appears as grey on IOS when using the input[type="submit"]

Why does the submit input look different on IOS only, and how can this be resolved? https://i.sstatic.net/UVlKB.png Thank you in advance For HTML: <input class="btn" type="submit" [disabled]="" ...

Switch the navbar background color from see-through to black

On my website, I have set up a navbar navigation that transitions between a transparent background and a black background as the user scrolls down. However, I would like the black background to be present at all times for the navbar. I built the website us ...

Adjusting the color of a cell based on its value

Currently, I am in the process of converting a CSV file to an HTML table by utilizing a tool available at . However, I am facing a challenge in modifying the background color of cells based on their values. I would greatly appreciate any help or guidance w ...

What's the best way to avoid global application of stylesheets imported for svelte carbon components?

My dilemma lies in wanting to utilize the DatePicker feature from carbon-components-svelte. Unfortunately, when I do so, the global application of styles from carbon-components ends up causing some conflicts with my own custom styles. As per the documenta ...

establish a distinct row color pattern for the initial column

I am currently working on a table that has sticky columns. I am trying to create alternating row colors in the first column only. Below is the code for the table: <div class="table-responsive"> <table class="table table-bordered table-stripe ...

SignalR enables the display of identical dashboard data pulled from queries on various browsers. By utilizing SignalR/hub, MVC, and C#.NET, the data can

Encountering an issue with my signalr/hub while fetching dashboard data. I'm using 2 browsers to access data based on dates. However, when searching for July on browser 1 and then switching to another month on browser 2, the data in browser 1 gets upd ...

Issue with Bootstrap's pull-right class causing elements to overlap

I need help positioning a single button above a list, with the button to the right. Whenever I try using the pull-right class on the button (or its containing div), the button ends up being covered by the list. <div> <div class="pull-right"& ...

Generating an HTML report that includes a header and footer on every page using Firefox

I have been trying different methods, but none of them seem to work properly. My issue is with printing a html report with a header and footer on every page specifically in Firefox. A Possible Solution: <html> <head> <title></title&g ...

Mobile Safari on iOS devices is known for its capability to overlay HTML5 <video> on top of everything

Although a similar question was asked 6 years ago without any answers, I am currently facing the same issue. Problem: The <video> tag in my Angular/Ionic application overlaps my image and two buttons in iOS Mobile Safari - no matter what I try! It ...

Bring in the SCSS directory from the overarching SCSS program

I am currently working with Angular (Jhipster) in my application and I am looking to include multiple .scss files in my global.scss file. To achieve this, I have created a folder called "util" at the same level as the global.scss file and placed these .scs ...

How to position the figcaption within a card?

My card design features a masonry-style layout similar to what you can see here https://codepen.io/daiaiai/pen/VPXGZx I'm trying to add some additional information on top of the images using figcaptions, but my attempts with position:relative haven&a ...