Arranging div elements side by side in a way that they slightly overlap each other

I'm trying to create a unique layout for a table of elements (pictures) where they are arranged horizontally and partially overlap to save space.

I've been experimenting with CSS to achieve this effect. Here's the code I've come up with:

<!DOCTYPE html>
<html>
    <head>
        <style>
            div.tableel
            {
                height : 100px;
                width : 100px;
        display: table-cell;
                position: relative;
            }
      div.tableel ~ div.tableel 
      {
        left: -30px;
        font-size: 24pt;
      }
      div.row
      {
        display: table-row;
      }
      div.table
      {
        display: table;
      }
        </style>
    </head>
    <body>
        <div class="table">
            <div class="row">
                <div class="tableel" style="background-color: red;">
          reg
                </div>
                <div class="tableel" style="background-color: blue;">
          ge
                </div>
                <div class="tableel" style="background-color: yellow;">
          rg
                </div>
            </div>
        </div>
    </body>
</html>

Although I was able to set the font successfully, I'm puzzled as to why the third element is not shifted to the left as expected.

Any help would be appreciated!

Answer №1

I'm confused about why the font is displaying correctly, but the third element isn't aligned to the left.

The alignment is actually working as intended.

The reason you may not perceive it properly is due to the gap created between the second and third div when the second one shifts to the left. The third div fills this space.

You can visualize this concept with this fiddle: http://jsfiddle.net/abhitalks/byayxob0/

If you want to maintain this layout, you'll need to adjust the positioning of the last div by double the amount:

div.tableel:last-child { left: -60px !important; }

Check it out here: http://jsfiddle.net/abhitalks/byayxob0/1/

However, managing this approach might become tricky if you have an unknown number of divs. You'd have to adjust the left property cumulatively, which CSS doesn't handle automatically.


An alternative and simpler method would be to keep the divs inline and utilize negative margins to control the overlap.

Demo Fiddle: http://jsfiddle.net/abhitalks/4gaotuwL/

Demo Snippet:

div.tableel {
    height: 100px; width: 100px;
    display: inline-block;
}
div.tableel:nth-child(1) { background-color: rgba(255,0,0,0.5); }
div.tableel:nth-child(2) { background-color: rgba(0,0,255,0.5); }
div.tableel:nth-child(3) { background-color: rgba(255,255,0,0.5); }
div.tableel:not(:first-child) {
    margin-left: -10px;
}
<div class="table">
    <div class="row">
        <div class="tableel">reg</div>
        <div class="tableel">ge</div>
        <div class="tableel">rg</div>
    </div>
</div>

Answer №2

The reason for this behavior is that the second element is initially moved 30px to the left in order to create a gap of 30px from the 3rd element. Consequently, when you shift the 3rd element by 30px to the left, it simply closes the gap that was created earlier. If your goal is to have the 3rd element overlap with the second element by 30px, then you would actually need to move it a total of 60px towards the left in order to catch up and achieve the desired overlap.

Answer №3

.table {
  width: 300px;
  table-layout: fixed;
  display: table;
}
.tableel {
  height: 100px;
  width: 100px;
  display: table-cell;
  position: relative;
  vertical-align: middle;
  text-align: center;
}
.row {
  display: table-row;
}
.default .tableel ~ .tableel {
  left: -30px;
}
/* I just adjusted the second block*/

.scene-1 .tableel:nth-child(2) {
  left: -30px;
}
.scene-2 .tableel:nth-child(2) {
  left: -30px;
}
/* I also shifted the third block by 60 pixels (since 30 pixels would make it overlap with the second block)*/

.scene-2 .tableel:nth-child(3) {
  left: -60px;
}
<h2>Your code</h2>
<div class="table default">
  <div class="row">
    <div class="tableel" style="background-color: rgba(255,0,0,0.7);">
      reg
    </div>
    <div class="tableel" style="background-color: rgba(0,255,0,0.7);">
      ge
    </div>
    <div class="tableel" style="background-color: rgba(0,0,255,0.7);">
      rg
    </div>
  </div>
</div>
<h2>Scene 1</h2>
<div class="table scene-1">
  <div class="row">
    <div class="tableel" style="background-color: rgba(255,0,0,0.7);">
      reg
    </div>
    <div class="tableel" style="background-color: rgba(0,255,0,0.7);">
      ge
    </div>
    <div class="tableel" style="background-color: rgba(0,0,255,0.7);">
      rg
    </div>
  </div>
</div>
<h2>Scene 2</h2>
<div class="table scene-2">
  <div class="row">
    <div class="tableel" style="background-color: rgba(255,0,0,0.7);">
      reg
    </div>
    <div class="tableel" style="background-color: rgba(0,255,0,0.7);">
      ge
    </div>
    <div class="tableel" style="background-color: rgba(0,0,255,0.7);">
      rg
    </div>
  </div>
</div>

Answer №4

To shift 30 pixels to the left from the second element, apply left: -60px; to the third element.

Answer №5

UPDATE If you find yourself dealing with an unspecified number of divs and want the code to work seamlessly regardless of how many divs you have, consider using a negative margin approach.

Instead of:

            div.tableel {
            height : 100px;
            width : 100px;
            display: table-cell;
            position: relative;
        }

Use this instead:

            div.tableel {
            height : 100px;
            width : 100px;
            display: inline-block;
            position: relative;
        }

Then apply a negative margin to the blocks by replacing:

     div.tableel ~ div.tableel 
  {
    left: -30px;
    font-size: 24pt;
  }

with:

            div.tableel {
            font-size: 24pt;
            opacity: 0.5;
            margin-left: -30px;   
        }

To clarify further, consider the following part of your code:

      div.tableel ~ div.tableel 
  {
      position: relative;
    left: -30px; /* <------------------This */
    font-size: 24pt;
  }

The issue arises when attempting to adjust the left positioning value within the code snippet. By reevaluating the box sequence, Box 1, 2, and 3 may require individual adjustments for optimal alignment.

A recommended adjustment would involve:

   div.tableel{   
    font-size: 24pt;
  }
  div.tableel:nth-child(2){
    left: -30px;
  }
  div.tableel:nth-child(3){
    left: -60px;
  }

For a visual representation, refer to the provided Fiddle link.

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

Avoiding postbacks in an aspx page when submitting an email input data

Currently, I am working on an ASPX page (version 3.5) and attempting to implement HTML5 validation on it. <asp:TextBox ID="AccountantEmail" CssClass="form-control" type="email" runat="server" required /> Upon rendering, the appearance of this contr ...

Retrieve random data from text fields after clicking the button, using .txt and .csv files

Looking to incorporate an HTML text field on my website. I have a list of names stored in either a txt or csv file, and I want to be able to display a randomly selected name from the list in that field upon clicking a button. ...

HTML Remover resulting in a malfunction

Currently in the process of removing HTML tags from text using the following method: <p><b>Masala</b> films of <a href="/wiki/Cinema_of_India" title="Cinema of India">Indian cinema</a> are those that combine different genres ...

Experiencing issues where an undefined value is being returned while attempting to pass a selected value

I'm facing a minor issue with my JavaScript code. Below is the form structure I am working with: <form method="get" name="basic" id="basicId" action="/page2"> <select id="activity" name="activity" class="form-control inputbox"> ...

pick out particular values from an array

I have a question that may seem basic to some, but I'm curious about how to select specific elements from an array. In this case, I have an array with 100 elements: var cubes = [element1, element2, element3 ...] and I want to select elements 25-35. ...

Unable to achieve full width for a div within a scrollable container

Currently, I am in the process of constructing a new website using Gatsby.js. However, I have encountered a minor issue with some CSS related to code blocks. Since CSS is not my strong suit, I have been unable to resolve it thus far. Below is a runnable sn ...

Adding multiple styles to a directive in Angular 6 can be achieved by using the addClass method. It is important to note that the

One of my directives triggers an action when I scroll. @HostListener('window:scroll') doSomething() { console.log(this.el); console.log(this.el.nativeElement); if (window.pageYOffset > 10) { console.log('mouse ...

Using jQuery to make an Ajax post request that will load the current page with additional form data appended to the

Below is the HTML code for my registration form: <form id="registerForm"> <input type="text" pattern="[A-Za-z]{1,20}" placeholder="First Name" name="guestFName" title="Up to 20 alphabetical characters" required> <inp ...

Struggling to float <aside> to the left of <article> for proper alignment?

tldr; I'm attempting to position the aside-section to the left of the article-section (similar to a sidebar/side column), but my "float" property doesn't seem to be working at all. Is there a way to achieve this without modifying the HTML code an ...

Is there a case of Bootstrap Offcanvas fade appearing twice in various sections of the website?

Currently in the process of updating my website using Ruby on Rails, I was given the task of integrating Bootstrap instead of using custom CSS styling. While this change posed no issue, a problem arose when I implemented the Offcanvas menu from Bootstrap. ...

Utilize JQuery to transfer a cell that currently resides in one row to a new row

I need to relocate a cell within a table from one row to another. The table currently has only one row with four cells, and I specifically want to move the third cell to a new row. Here is the existing markup: <table class="sbtable"> <tbody> ...

Iframes are not compatible with JQuery UI dialogs

After attempting to open a URL within an Iframe in a JQuery dialog box, I encountered the following issue: Here is the code snippet that I used: http://pastebin.com/Wqf0mGhZ I am looking for a solution to make sure that the dialog displays all of the con ...

Refreshing HTML content using event delegation in JavaScript

Currently, I am attempting to dynamically load additional HTML content onto my webpage when a button is clicked. Here is the code that I have implemented so far: Main HTML Code: <div class="row" id="gallery-wrapper" > <di ...

Exploring the features of AngularJS with a secure login page

I need some guidance on the best way to create a login page. Currently, I have set up a ng-view root ("/login") in my app.js file. The issue I am facing with this approach is that I have to include static HTML in other files using ng-include. (This stati ...

``Are there any thoughts on how to troubleshoot display problems specifically on mobile

Whenever I use Safari on iOS for my web application, I encounter strange rendering issues. It's odd because the majority of the time everything functions as it should, but every now and then these bugs crop up with no discernible pattern. Examples th ...

What is the best way to arrange my crimson blocks to sit next to each other?

Is there a way to align the red boxes side by side with some space in between them for separation, and how can I ensure that the signin/signup button appears against the blue background of the header? I attempted using float but encountered issues. The d ...

Is there a way to ensure that a "loop once" animated GIF background will replay on each page refresh or load?

I currently have an animated GIF file set as the background image for my div, which was specifically configured in Photoshop to loop only once. Therefore, it only plays on the initial page load. Is there a way to reset the background image upon page refre ...

Javascript keycode used to target the element when a key is pressed

In my current project, I am utilizing a code snippet to attach a KeyDown event handler to any element within the HTML form. for(var i=0;i<ele.length;i++) { ele[i].onkeydown = function() { alert('onkeydown'); } } I am ...

Placing text alongside an image at the top of the page

Here's the HTML code generated by JSF: <div align="center"> <img src="images/background_image.jpg" height="200px" width="30%" style="vertical-align: top"/> <span style=""> Welcome abc, <input type= ...

Implementing 3D features within a 2D HTML5 canvas

I am working on a 2D game project that utilizes the power of HTML5 Canvas. My goal is to incorporate 3D characters into the 2D canvas. One idea I'm considering is using THREE.js on separate "hidden" canvases, dedicating one canvas to each 3D characte ...