Having trouble getting my floating divs to stay centered within my container using CSS, even after removing float: left

Struggling to get CSS working correctly? I'm having an issue with a display panel that shows 1-4 cells with text/image in each row. Everything works fine with at least four cells, but when there are less than 4 (display=none), the cells align to the left and I want them centered.

Here's a visual representation to help understand:

https://i.sstatic.net/yHsW5.jpg

Here is the HTML and CSS I have so far:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script src="OEPanel.js"></script>
        <link rel="stylesheet" href="./OEPanel.css">
    <title>Document</title>
</head>

<body>
    <div id="oepanelcontainer" class="OEContainer clearfix">
        <div id="oepanel" class="OEItems clearfix">
            <div id="oecell1" class="OECell"></div>
            <div id="oecell2" class="OECell"></div>
            <div id="oecell3" class="OECell" style="display:none;" ></div>
            <div id="oecell4" class="OECell" style="display:none;" ></div>
        </div>
    </div>
</body>
</html>

CSS:

.OEContainer {
    background-color: beige;
    min-height: 10em;
    vertical-align: middle;
    padding: 10px;
    max-width:1130px;
    margin:auto;
    text-align:center;
    justify-content:space-between;
}

.OEItems {
    min-height: 10em;
    vertical-align: middle;
    padding: 0px;
    max-width:1130px;
    margin:auto;
    text-align:center;
    justify-content:space-between;
}

.clearfix::after { /* clearfix class to expand the element back to its normal height */
    content: '';
    display: block;
    clear: both;
}
  
.OECell {
    background-color: lightblue;
    min-height: 10em;
    vertical-align: middle;
    padding: 0px;
    width:250px;
    text-align:center;
    /* float: left; */
    margin: 5px;
}

@media (max-width: 500px) {
    .OEContainer {
        flex-direction: column;
        align-items: center;
    }
}

Any assistance is appreciated! Thank you!

IMPORTANT NOTE: I noticed that until a certain width (around 850px), the blocks center properly. However, once the width exceeds this, the blocks suddenly shift to the far left.

Answer №1

To center the items, simply apply display: flex; and justify-content: center; to the direct parent of these items (specifically, to #oepanel). No need for floating elements.

Additional tip: You can incorporate a media query to include flex-wrap: wrap; in the same rule under a specific width condition. (demonstrated below in your customized media query)

.OEContainer {
  background-color: beige;
  min-height: 10em;
  vertical-align: middle;
  padding: 10px;
  max-width: 1130px;
  margin: auto;
  text-align: center;
  justify-content: space-between;
}

#oepanel {
  display: flex;
  justify-content: center;
}

.OEItems {
  min-height: 10em;
  vertical-align: middle;
  padding: 0px;
  max-width: 1130px;
  margin: auto;
  text-align: center;
  justify-content: space-between;
}

.clearfix::after {
  /* clearfix class to expand the element back to its normal height */
  content: '';
  display: block;
  clear: both;
}

.OECell {
  background-color: lightblue;
  min-height: 10em;
  vertical-align: middle;
  padding: 0px;
  width: 250px;
  text-align: center;
  /* float: left; */
  margin: 5px;
}

@media (max-width: 500px) {
  .OEContainer {
    flex-direction: column;
    align-items: center;
  }
  #oepanel {
    flex-wrap: wrap;
  }
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
  <script src="OEPanel.js"></script>
  <link rel="stylesheet" href="./OEPanel.css"></script>
  <title>Document</title>
</head>

<body>
  <div id="oepanelcontainer" class="OEContainer clearfix">
    <div id="oepanel" class="OEItems clearfix">
      <div id="oecell1" class="OECell"></div>
      <div id="oecell2" class="OECell"></div>
      <div id="oecell3" class="OECell" style="display:none;"></div>
      <div id="oecell4" class="OECell" style="display:none;"></div>
    </div>
  </div>
</body>

</html>

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 HTML tabs using jQuery with input[type="radio"] tutorial for beginners

I'm having trouble creating a tab with input[type="radio"] using Jquery. The tab works fine on the first click, but it doesn't work on the second click. I can't figure out where the issue is in the Jquery code. Can someone assist m ...

HTML/Angular tutorial: Sharing an On-Click value with a different HTML element within the same component

As a newcomer to this, I could really use some guidance. Currently, I have a Mat Table that is displaying a specific range of data from my firestore. My goal is to be able to click on a particular row and have its data appear in a list below the table. I ...

Guide to making a sliding animation appear when hovering over a menu using jQuery

I have noticed a common feature on many websites, but I am unsure of how to explain it. At times, there are sliding elements in the navigation, like an arrow under menu items that moves when the user hovers over different links. Here is an example of a s ...

Can Selenium successfully scrape data from this website?

I am currently attempting to extract Hate Symbol data (including the name, symbol type, description, ideology, location, and images) from the GPAHE website using Selenium. As one of my initial steps, I am trying to set the input_element to the XPATH of the ...

HTML Element Split in Two by a Line in the Middle

Greetings to all, after observing for a while I have decided to make my first post here (and just to clarify, I am an electrical engineer, not a programmer). I am in search of creating a unique element in HTML where I can detect clicks on both its upper a ...

Tips for setting up personalized breakpoints for a Bootstrap navbar

I am currently facing an issue with my navbar on tablet view. Despite implementing custom breakpoints to collapse the navbar at 1050, the menu bar is appearing in two rows instead of one. I have tried using the code below but it doesn't seem to be wor ...

JavaScript - AngularJS HTML parser

I am working with an array that contains content along with HTML tags, and here is the code snippet: for (car in cars.parking[0]){ content.push('<br />'); for (token in cars.parking[0].now) { content.pus ...

Achieve a full-height sidebar design similar to Wordpress using flexbox functionality

Working on a web app that features a tools sidebar with a fixed width requirement amidst fluid content. Explored using flexbox to achieve this, but encountered an issue where the main box only takes the height of the viewport instead of the entire site&ap ...

Creating a perpetual loop animation for two divs moving from right to left endlessly

Here is the code I have: HTML <div class="screen screen1"></div> <div class="screen screen2"></div> CSS .screen{ width: 100%; height: 50%; position: absolute; background-color:#001; background-image: radial- ...

`Changing the iframe content dynamically with next and previous buttons: a step-by-step guide`

function displayPDF(fileSlNo){ var data = { pageMode: "PDF_DISPLAY", fileSlno: fileSlNo }; var d = $.param(data); var request = $ .ajax({ type: "GET", url:"folderNavigation.do?"+d, dataType : "TEXT", success: functio ...

What is the process for inserting an image into a table using el-table and el-table-column components in Vue.js while utilizing ui-elements?

I'm new to Vue.js and successfully built a basic table using the ui-element. The el-table element was utilized for constructing the table, with columns displayed using el-table-column and prop (see code below). Now, I want to incorporate images/avatar ...

Using Angular to showcase the names of uploaded files within an HTML document

I successfully developed an application that uses a post request to upload files to an API. Service file: onFileSelected(event){ this.selectedFile = <File>event.target.files[0]; } onUpload() { const formdata = new FormData(); formdata ...

Stop the initial expansion of the first accordion with JavaScript on page load

I have a simple accordion created using only pure javascript without jQuery and Pure CSS. Everything is functioning correctly, but the problem I am facing is that the first accordion is automatically expanded when the page loads. I have tried various metho ...

Place an overlay element in the top-left corner of a perfectly centered image

Currently, there is an image that is centered on the screen using flexbox: .center-flex { display: flex; justify-content: center; } <div class="center-flex"> <img id="revealImage"> </div> An attempt is be ...

What is the reason behind changing the line-height for one inline-block sibling div affecting both divs?

Here's my setup: <div> <div style="display:inline-block; ">div_1</div> <div style="display:inline-block; line-height:20px;">div_2</div> </div> Why does setting the line-height property f ...

Unable to locate the Bootstrap CSS file when deploying on PythonAnywhere

I recently created an admin panel that integrates with a database. To automate the process of generating the admin panel, I utilized flask-admin. Running the server locally on my PC displayed the bootstrap swatch correctly and everything worked seamlessly. ...

The applied style of NextUI Components may be inconsistent, appearing to not apply in certain instances even though it does work

I've hit a roadblock trying to solve this issue. While using NextUI, I've managed to successfully apply styles to some components like the navbar, indicating that I have correctly installed NextUI and configured Tailwind. However, I'm facing ...

What is the best way to incorporate a <c:forEach> loop into JSP operations?

I am attempting to calculate the product of two variables that are associated with an item in a loop. Below is the code snippet from the JSP file: <table> <thead> <tr> <th>PRICE</th> <th ...

Styling with CSS using only numerical values

My website features a section that states "Weekdays 10:00 ~ 18:00 /*linebreak/ Saturdays 10:00 ~ 13:30" I am looking to format only the numerical values in the font "Courier New," specifically the "10:00 ~ 18:00" and "10:00 ~ 13:30" sections. The remainin ...

"Hovering over one div does not trigger the display of another div

I seem to have forgotten my CSS skills, but I am facing an issue. Here is the code snippet: <div class="footer_container"> <div class="website_logo_to_footerexpand"></div> <div class="info_cont"> <div class ...