Can a div with float: left; be centered?

Currently, I am attempting to create a dock (similar to the iOS dock) for my website. Below is the full code that I have implemented:

function addPrevClass(e) {
  var target = e.target;
  if (target.getAttribute('src')) { // check if it is img
    var li = target.parentNode.parentNode;
    var prevLi = li.previousElementSibling;
    if (prevLi) {
      prevLi.className = 'prev';
    }
    
    target.addEventListener('mouseout', function() {
      prevLi.removeAttribute('class');
    }, false);
  }
}
if (window.addEventListener) {
  document.getElementById("dock").addEventListener('mouseover', addPrevClass, false);
}
li {
  float: left;
}
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: rgba(255, 255, 255, 0.05);
}
#dock li img {
  width: 64px;
  height: 64px;
  -webkit-box-reflect: below 2px -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(0.7, transparent), to(rgba(255, 255, 255, .5)));
  /* reflection is supported by webkit only */
  -webkit-transition: all 0.3s;
  -webkit-transform-origin: 50% 100%;
}
#dock li:hover img {
  -webkit-transform: scale(2);
  margin: 0 2em;
}
#dock li:hover + li img,
#dock li.prev img {
  -webkit-transform: scale(1.5);
  margin: 0 1.5em;
}
#dock-container ul {
  text-align: center;
}
<div id="dock-container">
  <div id="dock">
    <ul>
      <li>
        <a href="http://android.com">
          <img src="https://dl.dropboxusercontent.com/u/1330446/demo/dock/images/dock-icons/palm.png" />
        </a>
      </li>
      <li>
        <a href="http://palm.com">
          <img src="https://dl.dropboxusercontent.com/u/1330446/demo/dock/images/dock-icons/palm.png" />
        </a>
      </li>
      <li>
        <a href="http://android.com">
          <img src="https://dl.dropboxusercontent.com/u/1330446/demo/dock/images/dock-icons/palm.png" />
        </a>
      </li>
      <li>
        <a href="http://palm.com">
          <img src="https://dl.dropboxusercontent.com/u/1330446/demo/dock/images/dock-icons/palm.png" />
        </a>
      </li>
      <li>
        <a href="http://android.com">
          <img src="https://dl.dropboxusercontent.com/u/1330446/demo/dock/images/dock-icons/palm.png" />
        </a>
      </li>
      <li>
        <a href="http://palm.com">
          <img src="https://dl.dropboxusercontent.com/u/1330446/demo/dock/images/dock-icons/palm.png" />
        </a>
      </li>
      <li>
        <a href="http://android.com">
          <img src="https://dl.dropboxusercontent.com/u/1330446/demo/dock/images/dock-icons/palm.png" />
        </a>
      </li>
    </ul>
    <div class="base"></div>
  </div>
</div>

However, I am facing an issue with the alignment of my dock on the website. Removing the "float: left;" property results in a vertical orientation of the dock. How can I center the dock while keeping it horizontal? Any suggestions or solutions would be greatly appreciated.

Answer №1

To suit your requirements, replace float:left with display: inline; or display: inline-block for li:

li {
  display: inline;
}

Answer №2

If you're struggling with making the ul element shrink based on its content and still maintain block behavior, one way to achieve this is by utilizing the display:table; property along with setting margin:auto;.

function addPrevClass(e) {
  var target = e.target;
  if (target.getAttribute('src')) { // make sure it's an image
    var li = target.parentNode.parentNode;
    var prevLi = li.previousElementSibling;
    if (prevLi) {
      prevLi.className = 'prev';
    }

    target.addEventListener('mouseout', function() {
       prevLi.removeAttribute('class');
    }, false);
  }
}
if (window.addEventListener) {
  document.getElementById("dock").addEventListener('mouseover', addPrevClass, false);
}
li {
   float: left;
}
ul {
   display: table;
   margin: auto;
   list-style-type: none;
   /*margin: 0;*/
   padding: 0;
   overflow: hidden;
   background-color: rgba(255, 255, 255, 0.05);
}
#dock li img {
   width: 64px;
   height: 64px;
   -webkit-box-reflect: below 2px -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(0.7, transparent), to(rgba(255, 255, 255, .5)));
   /* reflection works in webkit only */
   -webkit-transition: all 0.3s;
   -webkit-transform-origin: 50% 100%;
}
#dock li:hover img {
   -webkit-transform: scale(2);
   margin: 0 2em;
}
#dock li:hover + li img,
#dock li.prev img {
   -webkit-transform: scale(1.5);
   margin: 0 1.5em;
}
#dock-container ul {
   text-align: center;
}
<div id="dock-container">
   <div id="dock">
     <ul>
        <li>
           <a href="http://android.com">
             <img src="https://dl.dropboxusercontent.com/u/1330446/demo/dock/images/dock-icons/palm.png" />
           </a>
        </li>
        .... [remaining code truncated for brevity]....
        </li>
     </ul>
     <div class="base"></div>
   </div>
</div>

Answer №3

To ensure there is no gap between list items while keeping the float: left, you can apply the following CSS:

#dock {
    text-align: center;
}

ul {
    display: inline-block;
}

Answer №4

Utilizing css3 can truly make a difference in your design. Implement the code snippet below to see the impact:

#container{
  display: grid;
  place-items: center;
}

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

Is there a way to implement seamless scrolling within an absolute element using Jquery?

Hey there! I recently implemented smooth scrolling on my website, but it seems to only work on single-page layouts. How can I make it function properly within an absolutely positioned scrollable element? Here are the link to my website and the correspond ...

Having trouble with asynchronous JSON calls in JavaScript when setting async to false

I'm having trouble figuring out what I'm doing wrong in this scenario. The issue is that I can't seem to reassign the variable poster_path with the fetched poster-path from the JSON call. What's puzzling to me is that I even tried setti ...

Trouble with displaying days on the Datepicker

I'm currently facing an issue with my datepicker. I have a specific set of days that should be highlighted on the calendar, and it needs to be constantly updated. For example, past days are removed from the calendar automatically to keep it current. H ...

Sending input values from textboxes to the Controller

I currently have the following code snippets: Home Controller: public IActionResult Index() { return View(); } public ActionResult Transfer() { string path = @Url.Content(webRootPath + "\\SampleData\\TruckDtrSource.json&q ...

What is the best way to add bootstrap tooltips to my website?

I'm looking for guidance on how to get this project up and running smoothly. The instructions on the bootstrap site were not very clear, particularly regarding setting up tooltips for links on my website. Any advice or tips would be greatly appreciate ...

Certain public files in Express cannot be accessed locally

While running my Node.js application on localhost, I am able to access http://localhost:3000/css/dashboard.css without any issues. However, when attempting to access http://localhost:3000/css/logo.png for a logo image in the same directory, all I receive i ...

Aligning a tri-column design

I'm encountering an issue with this code that's preventing it from running properly on Google Chrome (I haven't tried other browsers). When the content displays, the regular paragraphs appear aligned to the far left instead of being centered ...

Blurry font rendering occurs when an element is scaled using CSS

I want to add a scale animation to a bootstrap button, but the text appears blurry. I've tried all the solutions mentioned here. How can I resolve this issue? Below is the code snippet (text is slightly less blurry in the snippet compared to my pr ...

What is the best way to incorporate line breaks into a reportlab PDF created in HTML format?

Currently, I am facing a challenge in generating PDFs using reportlab. The data that needs to be displayed is fetched from a dataframe. However, one field contains a lengthy text that requires breaklines for better readability in the PDF. Below is the sni ...

Display the option to "Delete" the link only when there are multiple images in my image collection

I am using jQuery and Ajax to remove banner images from my website. However, I want to make sure that if there is only one image left, it cannot be deleted. Each image in the list has a corresponding delete link: echo '<a class="delete j_bannerd ...

Is it possible to conceal glyphicons by employing the attribute hidden="hidden"?

Is it possible to conceal a glyphicon icon in this manner? <i class="glyphicon glyphicon-remove-circle" title="Please add a suitable value" id="author" hidden="hidden"></i> <p>Author</p> ...

Server not recognizing nested routes in React-Router

I am currently using Express.js to render a React application on the server side, but I have encountered an issue where some of my routes are getting skipped over unexpectedly. Here is my server.js: app.get('*', (req, res) => { conso ...

Troubleshooting AngularJS POST Request Error with Request Body

I am a beginner in AngularJs and I am trying to make a post request to a server with enum form. Currently, I have the following JavaScript code: function completeTaskAction2($scope, $http, Base64) { $http.defaults.headers.common['Authorization'] ...

I'm looking to use JQuery's .load function to transfer content from one URL to another

I am looking to dynamically load content from a div with the ID maininner on a specific URL within my website into another div with the ID yurt1_avail on a different URL also on the same site. I have conducted a successful test outside of the CMS using ...

Transferring a uint8clampedarray Array to C# using JavaScript via ajax after extracting getImageData from the Canvas

Currently, I am facing an issue while attempting to create a signature using client-side javaScript and then forwarding the result to the back-end (c#) via ajax. The array I am trying to transmit is of the type uint8clampedarray, but unfortunately, the Set ...

Pressing a button triggers the highlighting of a tab in HTML through the use of Javascript

In the corner of my webpage, I have three tabs: info, question, order. When I click on one tab header, only that tab should highlight. The info section includes two buttons that link to the question and order tabs. When these buttons are pressed, the respe ...

Why isn't any of my AngularJS code running as expected?

I've recently started learning AngularJS, but I'm encountering an issue where none of my code is being executed when I run the page. Instead, all I see on the website is {{angular-message}} and I'm receiving the error "Error: [ng:areq] Argum ...

The user's input is not being accurately represented when making an AJAX request to the

When attempting to incorporate a user's city input (e.g. Los Angeles) into Ajax URL parameters, there seems to be an issue where the '+' is not being added between "los angels", resulting in a broken URL when console.log(searchURL) is used. ...

Testing React Hooks in TypeScript with Jest and @testing-library/react-hooks

I have a unique custom hook designed to manage the toggling of a product id using a boolean value and toggle function as returns. As I attempt to write a unit test for it following a non-typescripted example, I encountered type-mismatch errors that I' ...

Encountering a duplicate key error in ExpressJS collection

Whenever I try to create a new event with categories that already exist in my database, such as creating an event with the category "javascript" and then attempting to create another event with categories "javascript, html, css", I encounter the error mess ...