[英]Vertically centering an element with CSS
我正在尝试在div中垂直居中放置内容。
HTML:
<div id="header">
<div class="col-xs-1 col-sm-1 col-md-1 col-lg-1" id="logo-img-div"><img id="logo-img" src="logo.png"></div>
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3" id="logo-text">Text</div>
</div>
CSS:
@media only screen and (min-width: 768px) {
.col-sm-1 {width: 8.33%; float: left;}
.col-sm-2 {width: 16.66%; float: left;}
.col-sm-3 {width: 25%; float: left;}
.col-sm-4 {width: 33.33%; float: left;}
.col-sm-5 {width: 41.66%; float: left;}
.col-sm-6 {width: 50%; float: left;}
.col-sm-7 {width: 58.33%; float: left;}
.col-sm-8 {width: 66.66%; float: left;}
.col-sm-9 {width: 75%; float: left;}
.col-sm-10 {width: 83.33%; float: left;}
.col-sm-11 {width: 91.66%; float: left;}
.col-sm-12 {width: 100%; float: left;}
}
* {
color: #2c2c2c;
height: 100%;
width: 100%;
margin: 0 !important;
font-family: 'Raleway';
}
#header {
height: 10%;
background-color: #2c2c2c;
color: #c4c3c3;
font-family: 'title';
}
#logo-img {
height: 80%;
width: auto;
}
#logo-img-div {
}
#logo-text {
color: #c4c3c3;
}
我想将logo-img-div和logo-text的内容居中,但将这两个div保留在标题内容的左侧。 我发现了许多类似的问题,但是没有一种解决方案有效。
您正在使用*将属性应用于所有选择器。 http://www.w3schools.com/cssref/css_selectors.asp由于边距为0,因此无法对齐div元素。
通常,您可以使用margin-left或right并移动许多px或em ...
尝试删除(*)元素的边距。 这不允许您对齐它们,因为空白是包括身体本身在内的所有其他元素之间的距离。 或者您可能只为左右留有边距:
* {
color: #2c2c2c;
height: 100%;
width: 100%;
margin-left: 0 !important;
margin-right: 0 !important;
font-family: 'Raleway';
}
如果您尝试将ID为“ header”的div垂直居中,请尝试以下操作:
#header{
position: relative;
top: 40%;
height:10%
background-color: #2c2c2c;
color: #c4c3c3;
font-family: 'title';
}
尝试以%为单位找到元素的高度,以便可以从50%的测量值中减去它们。 这样可以使您的元素完美居中。 在这种情况下,由于高度设置为10%,因此50%将转换为10%。
使用flex对齐子项。 哦,您可能不想将所有东西的高度和宽度都设置为100%。
@media only screen and (min-width: 768px) { .col-sm-1 {width: 8.33%; float: left;} .col-sm-2 {width: 16.66%; float: left;} .col-sm-3 {width: 25%; float: left;} .col-sm-4 {width: 33.33%; float: left;} .col-sm-5 {width: 41.66%; float: left;} .col-sm-6 {width: 50%; float: left;} .col-sm-7 {width: 58.33%; float: left;} .col-sm-8 {width: 66.66%; float: left;} .col-sm-9 {width: 75%; float: left;} .col-sm-10 {width: 83.33%; float: left;} .col-sm-11 {width: 91.66%; float: left;} .col-sm-12 {width: 100%; float: left;} } * { color: #2c2c2c; margin: 0; font-family: 'Raleway'; } html, body { height: 100%; } #header { height: 10%; background-color: #2c2c2c; color: #c4c3c3; font-family: 'title'; display: flex; align-items: center; } #logo-img { height: 80%; width: auto; } #logo-text { color: white; }
<div id="header"> <div class="col-xs-1 col-sm-1 col-md-1 col-lg-1" id="logo-img-div"><img id="logo-img" src="logo.png"></div> <div class="col-xs-3 col-sm-3 col-md-3 col-lg-3" id="logo-text">Text</div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.