Margin: 0 automatic positioning does not work on divs

For some strange reason, centering divs using margin: 0 auto does not work. My code is:

HTML:

<!DOCTYPE html>

<html>

<head>
<meta charset="utf-8">
<title>Picture Gallery</title>

<link rel="stylesheet" href="css/week7.css">

</head>

<body>

<h1>The Mighty Avengers</h1>



<div class="slide1">
    <img src="images/hawkeye.jpg" alt="Hawkeye" />
    <img src="images/capmar.jpg" alt="Captain Marvel" />
    <img src="images/beast.gif" alt="Beast" />
    <img src="images/thor.jpg" alt="Thor" />
</div>

 <div class="slide2">
    <img src="images/cap.jpg" alt="Captain America" />
    <img src="images/ant.jpg" alt="Ant Man" />
    <img src="images/vision.jpg" alt="The Vision" />
    <img src="images/scar.jpg" alt="Scarlet Witch" />
</div>



</body>

</html>

and CSS:

html {
background-color: gray;
}

h1 {
text-align: center;
}

img {

height: 250px;
margin-left: -20px;
width: 250px;
}

.slide1, .slide2 {
display: block;
margin: 0 auto;
width: 85%;
}

None of the other instances of this type of centering that Stack talked about helped. I tried this with and without the type of mapping set to classes, to no avail. Any understanding of this would be appreciated.

+4
source share
4 answers

This is because your image is 150px .. and your div is 80% of the document

You can fix this by doing text-align: center; on .slide1, .slide2.

+1
source

-, margin: 0 auto; , . , , , :

img:first-child {
    margin-left: 0;
}

.slide1, .slide2 {
    display: block;
    margin: 0 auto;
    width: 85%;
    text-align: center;
}
+1

What are you trying to achieve? Your slide divs are centered. I applied a yellow frame to them so you can see.

.slide1, .slide2 {
  display: block;
  margin: 0 auto;
  width: 85%;
  border:1px solid yellow;
}

I also updated your img css to make it more responsive so that the images do not wrap in the second line.

img {
  height: auto;
  width: 25%;
  max-width:250px;
}

https://jsfiddle.net/Lmmb03ck/4/

Hope this helps.

+1
source

I think this is what you are looking for:

:

HTML : No change

CSS

html {
background-color: gray;
}

h1 {
text-align: center;
}

img {

height: 250px;
margin-left: -2px; /* So that it resides side by side*/
width: 250px;
}

.slide1, .slide2 {
display: block;
margin: 0 auto;
width: 500px; /* As you are having 250px for each image */        
}
0
source

Source: https://habr.com/ru/post/1613133/


All Articles