为什么保证金:自动;不工作?

时间:2016-05-18 09:09:26

标签: javascript html css

即使我添加了保证金:auto; .content类实际上是模态的内容,它仍然位于左上角。为什么会这样?我怎样才能将它对齐?

var mod=document.getElementById("myModal");
var img= document.getElementById("image");
img.addEventListener("click",animate);
function animate() {
	mod.style.display = "block";
}
#image {
    width: 400px;
	cursor: pointer;
}
.modal {
	display: none;
	position: fixed;
	left: 0;
	top: 0;
	width: 100%;
	height: 100%;
	z-index: 1;
    background-color: rgba(0,0,0,0.9);
}
.content {
	margin: auto;
	width: 800px;
	animation-name: zoom;
	animation-duration: 0.6s;
}
@keyframes zoom {
	from {transform: scale(0.1);} 
    to {transform: scale(1);}
}
<html>
    <head>
	    <link rel="stylesheet" href="style.css">
	</head>
	<body>
	    <img id="image" src="http://i.telegraph.co.uk/multimedia/archive/03589/Wellcome_Image_Awa_3589699k.jpg">
		<div id="myModal" class="modal">
			<img class="content" id="image01" src="http://i.telegraph.co.uk/multimedia/archive/03589/Wellcome_Image_Awa_3589699k.jpg">
		</div>
        <script src="script.js"></script>		
	</body>
</html>

3 个答案:

答案 0 :(得分:8)

默认情况下,<img>replaced inline element,因此您必须将其转换为block

因此,添加

display: block;

也是.content

的CSS

也就是说,.content的更新CSS就像是,

.content{
    display: block;
    margin: auto;
    width: 800px;
    animation-name: zoom;
    animation-duration: 0.6s;
}

答案 1 :(得分:0)

为.model类添加此text-align:center,如..

.modal {text-align: center;}

答案 2 :(得分:0)

在CSS中做了一些改动。这似乎解决了你的问题。

更改内容的css:

margin: auto;
display: block;
/* top: 0; */
width: 800px;
animation-name: zoom;
animation-duration: 0.6s;
top: 0;
left: 0;
right: 0;
bottom: 0;
position: absolute;

&#13;
&#13;
var mod=document.getElementById("myModal");
var img= document.getElementById("image");
img.addEventListener("click",animate);
function animate() {
	mod.style.display = "block";
}
&#13;
#image {
    width: 400px;
	cursor: pointer;
}
.modal {
	display: block;
	position: fixed;	
	width: 100%;
	height: 100%;
  top:0;
  left:0;
	z-index: 1;
    background-color: rgba(0,0,0,0.9);
}
.content {
	margin: auto;
    display: block;  
    width: 800px;
    animation-name: zoom;
    animation-duration: 0.6s;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    position: absolute;
}
@keyframes zoom {
	from {transform: scale(0.1);} 
    to {transform: scale(1);}
}
&#13;
<html>
    <head>
	    <link rel="stylesheet" href="style.css">
	</head>
	<body>
	   
		<div id="myModal" class="modal">
			<img class="content" id="image01" src="http://i.telegraph.co.uk/multimedia/archive/03589/Wellcome_Image_Awa_3589699k.jpg">
		</div>
        <script src="script.js"></script>		
	</body>
</html>
&#13;
&#13;
&#13;