user3654045 user3654045 - 1 month ago 25
CSS Question

Horizontal alignment of a div element

I am trying to horizontal align the

div
element with
.slider
class but applying
margin: 0 auto;
is not working. Also please, how to make the slider image responsive?



/* CSS Document */

.header {
background-image: URL("images/header_top.png");
height: 80px;
}
.logo {
float: left;
background-image: URL("images/header_logo.png");
color: white;
background-repeat: no-repeat;
height: 84px;
width: 264px;
}
body {
margin: 0px 0px 0px 0px;
background-image: URL("images/bg_blueprint.jpg");
width: 100%;
}
.container-main {
width: 100%;
text-align: center;
}
.slider {
background-image: URL("images/slider_photo.png");
background-repeat: no-repeat;
margin: 0 auto;
float: none;
height: 482px;
max-width: 100%;
}

<body>
<div class="container-main">

<div class="pure-u-1 pure-u-md-1 header">
<div class="logo"></div>
</div>

<div class="slider"></div>

</div>
</body>




Answer

Issue here is the slider div is taking max width of its container. In order for a div to align center within a container using margin:0 auto;. it itself should have a limited width and height that is smaller than it's container. So to make it center. Change the max-width:100% in the .slider class to have a width in pixels like max-width:350px;

Now to make the image responsive just add the background-size:contain; in the .slider class.

Here is the .slider class that will work as you want:

.slider{
 background-image: URL("http://placehold.it/350x150");
 background-repeat: no-repeat;
 background-size:contain;
 margin: 0 auto;
 float: none;
 height: 482px;
 max-width: 350px;
}