[英]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.