css and HTML tutorial: Centering a DIV element with CSS styles

I have exhausted all similar questions and solutions, but nothing seems to work for me. My goal is to center a DIV element using CSS, and I've tried options like text-align, margin auto, and inline-block with no success. The example code I am experimenting with online simply refuses to be CENTERED.

Below is the CSS code I am working with:

@import url('https://fonts.googleapis.com/css?family=Poppins');
body, html{
margin: 0;
background: #ffffff;
font-family: 'Poppins', sans-serif;
}

h1{
text-align: center;
color:white;
}

.container-all{
width: fit-content;
margin: 20px auto;
height: auto;
}

.container{
width: calc(10% - 6px);
overflow:hidden;
height: fit-content;
margin:3px;
padding: 0;
display: block;
position:relative;
float:left;
}

img{
width: 100%;
transition-duration: .3s;
max-width: 100%;
display:block;
overflow:hidden;
cursor:pointer;
}

.title{
position:absolute;
display:block;
cursor:pointer;
top: 35%;
display: none;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%);
font-weight: bold;
font-size: 1.6em;
text-shadow: 1px 5px 10px black;
transition-duration: .3s;
}

.text{
 position:absolute;
 top: 70%;
 cursor:pointer;
 max-width: 80%;
 text-align:center;
 left: 50%;
 text-shadow: 1px 5px 10px black;
 font-size: 1em;
 display:none;
 margin-right: -50%;
 transition-duration: .3s;
 transform: translate(-50%, -50%) 
 }

 .container:hover img{
  transform: scale(1.2);
  transition-duration: .3s;
  filter: grayscale(50%);
  opacity: .7;
  }

  .container:hover span{
   color:white;
   display: block;
   transition-duration: .3s;
  }

  @media only screen and (max-width: 900px) {
  .container {
    width: calc(50% - 6px);
   }
   }
   @media only screen and (max-width: 400px) {
   .container {
      width: 100%;
    }
    }

This is how my HTML looks:

<!DOCTYPE HTML>
<html>
<head>
    <title>Gallery Testing</title>

    <link rel="stylesheet" type="text/css" href="gallery-test.css" />
</head>
<body>
<div class="container-all">
   <div class="container">
   <img src="https://images.freeimages.com/images/small-previews/d5d/powerlines-5-1389930.jpg" alt="">
   <span class="title">Lorem ipsum dolor</span>
<span class="text">Morbi diam viverra mattis sociis magna, habitasse penatibus non lectus</span>
</div>
<div class="container">
   <img src="https://images.freeimages.com/images/small-previews/d5d/powerlines-5-1389930.jpg" alt="">
<span class="title">Lorem ipsum dolor</span>
<span class="text">Morbi diam viverra mattis sociis magna, habitasse penatibus non lectus</span>
</div>
<div class="container">
<img src="https://images.freeimages.com/images/small-previews/d5d/powerlines-5-1389930.jpg" alt="">
<span class="title">Lorem ipsum dolor</span>
<span class="text">Morbi diam viverra mattis sociis magna, habitasse penatibus non lectus</span>
</div>

<div class="container">
<img src="https://images.freeimages.com/images/small-previews/d5d/powerlines-5-1389930.jpg" alt="">
<span class="title">Lorem ipsum dolor</span>
<span class="text">Morbi diam viverra mattis sociis magna, habitasse penatibus non lectus</span>
</div>
<div class="container">
<img src="https://images.freeimages.com/images/small-previews/d5d/powerlines-5-1389930.jpg" alt="">
<span class="title">Lorem ipsum dolor</span>
<span class="text">Morbi diam viverra mattis sociis magna, habitasse penatibus non lectus</span>
</div>
</div>

</body>
</html>

This shows the uncentered result: https://i.sstatic.net/Bx8xD.png

Here's an image illustrating what I'm aiming for: I edited the image to demonstrate my desired outcome. https://i.sstatic.net/ReaRX.png

Answer №1

To achieve the desired layout, please follow these steps:

  • For the Class .container-all, make sure to include text-align: center; in your CSS styles.
  • When styling the Class .container, remove float: left; and update display: block; to display: inline-block;.

A helpful resource has been prepared for you on JSFiddle

Answer №2

Make sure to implement these changes in the CSS code below.

@import url('https://fonts.googleapis.com/css?family=Poppins');
body, html{
margin: 0;
background: #ffffff;
font-family: 'Poppins', sans-serif;
}

h1{
text-align: center;
color:white;
}

.container-all{width: fit-content;margin: 20px auto;height: auto;text-align: center;}

.container{width: calc(10% - 6px);overflow:hidden;height: fit-content;margin:3px;padding: 0;display: inline-block;position:relative;float: none;}

img{
width: 100%;
transition-duration: .3s;
max-width: 100%;
display:block;
overflow:hidden;
cursor:pointer;
}

.title{
position:absolute;
display:block;
cursor:pointer;
top: 35%;
display: none;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%);
font-weight: bold;
font-size: 1.6em;
text-shadow: 1px 5px 10px black;
transition-duration: .3s;
}

.text{
 position:absolute;
 top: 70%;
 cursor:pointer;
 max-width: 80%;
 text-align:center;
 left: 50%;
 text-shadow: 1px 5px 10px black;
 font-size: 1em;
 display:none;
 margin-right: -50%;
 transition-duration: .3s;
 transform: translate(-50%, -50%) 
 }

 .container:hover img{
  transform: scale(1.2);
  transition-duration: .3s;
  filter: grayscale(50%);
  opacity: .7;
  }

  .container:hover span{
   color:white;
   display: block;
   transition-duration: .3s;
  }

  @media only screen and (max-width: 900px) {
  .container {
    width: calc(50% - 6px);
   }
   }
   @media only screen and (max-width: 400px) {
   .container {
      width: 100%;
    }
    }

If you want to float a div and still have it centered, make sure the parent element has a display property set to flex.

To center each container properly, first set their display property to inline-block instead of using fit-content for height. Then, apply text-center to the parent element to ensure proper centering as inline-block elements follow properties of both inline and block 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

Displaying JSON file data on an HTML webpage with the help of jQuery

Attempting to extract information from a JSON file and display it on an HTML document. Here is the code snippet: $(document).ready(function() { $.ajax({ type: "GET", url: "Beer.json", dataType: "json", success: processBeer, error: fu ...

What are some alternative ways to create a text field with the same style as Material UI's without relying on the Material UI

With the power of HTML, CSS, and Reactjs I am aiming to create a functionality where the placeholder animates up to the border upon clicking on the text field An example can be seen with Material UI text field: https://material-ui.com/components/text-fie ...

Creating a dropdown menu with HTML and CSS is causing me a major migraine

<div class="fbtop"> <img src="https://static.solidshops.com/1441/files/Logo-site.png" title="Pieke Wieke" alt="Pieke Wieke"> <h2 class="title">Handcrafted with love</h2> <ul class="dropdown"> <li> <a hre ...

Content in Tab Fails to Load due to IFRAME URL

On my web page, I have embedded an IFRAME with its src attribute set to load HTTPS content. This IFRAME is placed within a Bootstrap Nav-Tab Content, which in turn is located inside a Card element. Upon loading the webpage, I noticed that the content does ...

Modify the color of certain terms within the input field

I'm currently working on an editor for Cucumber feature files. As I write step definitions, I'd like the keywords Given, When, Then, etc. to appear in blue text, and any text between < > brackets to show up in red. Is there a way to change ...

Position the right div to float to the right with a dynamic width ahead of the left div in HTML to achieve

This particular challenge has proven to be quite difficult for me, and I have a feeling that I am overlooking something simple. My goal is to create a layout with a fixed-width left sidebar and a responsive variable-width content section on the right. Th ...

How do I create a Bootstrap 4 multi-level navigation bar that drops to the right on the third level?

clickable dropdown hover dropdown.jpg Source: Is there a way to create a dropdown menu that opens to the right like the clickable version, rather than to the left like the hover dropdown in the provided example? I'm open to other solutions as long ...

Creating a gap in an HTML document with a 'division' element and cascading style sheets

I am struggling to create a blank space between my divs. Despite trying numerous CSS properties such as margin-top, padding-top, and others from various sources online, I have not been successful. The only way I can add space is by using an excessive amou ...

Conceal content with transparent layer

Recently, I've been working on an animation where the logo is unveiled as a div moves downward. The div itself has a transparent background. I'm curious if it's feasible to hide parts of the logo behind the transparent div? <div class=" ...

Is there a way to customize the background color when the Bootstrap 4 toggle switch is in the "checked" position?

I'm struggling to find a way to adjust the background color of the "checked" state for this toggle switch in Bootstrap 4. It utilizes an additional library for toggling between dark and light modes - you can find it here on github. While that function ...

Unable to input data into the Database using an HTML Form combined with PHP

I am facing an issue with my MyPHP Database as no records are showing up when I execute these scripts. The environment I am using includes: APACHE 2.4.7 MYSQL 5.6.15 PHP 5.5.8 Let's start with the HTML Code... <html> <center> <f ...

When initially loaded, the Bootstrap Datepicker displays an inaccurate calendar

I implemented Bootstrap Datepicker to insert a date input field into my HTML document. Below is the code I used: HTML: <input type="text" name="manifest-date" class="calendar form-control" placeholder="M-d-yy" id="manifest-date" value="{{$currentDate} ...

Sticky Sidebar Attached to Parent Container with Smooth Sliding Effect

Is it possible to have my sidebar push the content across when opened, while keeping the fixed navigation relative to its parent element instead of the viewport? The sidebar works fine in Firefox but breaks out of the parent in Chrome. Link to JSFiddle & ...

Steps to customize the appearance of a button within a file input field

When implementing the file input in my code on a Mac, I noticed that the alignment appears off. On all other devices, it looks just fine. However, when I try to apply a style specifically to the 'Choose file' button, the style also gets applied t ...

How can you identify the resume of a web application once you return from opening the camera?

I'm working on a web application that utilizes the camera by following steps from this solution: How to access a mobile phone's camera using a web app? However, I am trying to figure out how to implement a callback function once the user return ...

What could be the reason that my Javascript function is not displaying in the HTML document?

I'm currently working on developing an HTML page that displays random quotes by Mark Twain. The function and array of quotes are set up in a separate Javascript file which is linked to the main HTML document. However, I am facing an issue where the ou ...

How can you position an image and text side by side without specifying the width using a div?

Having some trouble aligning an image (which is contained in a div) and some text (also in a div) on the same line without setting a width for the text. Here's what I've tried so far. <div id="container"> <div id="image" style="flo ...

What is the best way to verify HTML using RSS?

Looking to improve my skills in HTML/CSS/PHP development, I'm faced with a challenge when it comes to validating code that contains content beyond my control, such as an RSS feed. For instance, on my home page, which is a .php document containing bot ...

Array of materials for ThreeJS GLTFLoader

Attempting to load a model using GLTFLoader and apply different colors for each face of the object (cube) using a material array is not functioning as expected. var materials = [ new THREE.MeshPhongMaterial( {color: 0x552811,specular: 0x222222,shininess: ...

Issue with the appearance of the footer in my Wordpress template

After creating a WordPress template, I noticed that the footer is not extending to 100% width as expected. Check out the page here Any suggestions on why this might be happening? Could it be due to a missing closing div tag somewhere in the code? Thank ...