#html #css #flexbox
#HTML #css #flexbox
Вопрос:
Я пытаюсь создать заголовок для своего веб-сайта, используя html / css. Это то, чего я достиг до сих пор:
На этом фото показан весь элемент заголовка без обрезанных частей. Я пытаюсь расположить изображения и оба h1 и h2 по центру, при этом h1 и h2 центрируются вертикально между изображениями. Кроме того, я бы хотел, чтобы h2 располагался ближе под h1, намного больше, чем есть на самом деле. Вот мой текущий html / css:
* {
box-sizing: border-box;
}
html {
height: 100%;
font: 16px Geneva, Verdana, Helvetica, sans-serif;
}
body {
margin: 0px;
padding: 0px;
max-width: 1000px;
color: #0D1B1E;
}
body > header {
display: flex;
flex-flow: row nowrap;
margin: 0 auto;
background-color: #FAF9F4;
height: 100%;
}
.first {
padding: 5px;
flex: 1;
}
.second {
padding: 5px;
flex: 3;
}
.third {
padding: 5px;
flex: 1;
}
<header>
<div class="first">
<img src="images/header-logo1.png" alt="Law Enforcement Badge Logo" width="100" height="100">
</div>
<div class="second">
<h1>On Scene Academy</h1>
<h2>law enforcement training and tactics</h2>
</div>
<div class="third">
<img src="images/header-logo2.png" alt="Law Enforcement Badge Logo" width="100" height="100">
</div>
</header>
Будем признательны за любую помощь! Я также открыт для использования любых других методов отображения или позиционирования, отличных от flexbox. Спасибо!
Комментарии:
1. итак, что вы хотите сделать? расположить все по горизонтали и вертикали?
2. Да, и я бы хотел, чтобы h1 и h2 располагались по центру по горизонтали и вертикали между изображениями. Имеет ли это смысл?
3. добавьте
align-items: center
в свойheader
…
Ответ №1:
вот решение. Вам нужно использовать тег flex в заголовке и добавить свойство «align-items: center», чтобы расположить его по центру. Следующим образом;-
* {
box-sizing: border-box;
}
html {
height: 100%;
font: 16px Geneva, Verdana, Helvetica, sans-serif;
}
h1,h2{margin:0;}
body {
margin: 0px;
padding: 0px;
max-width: 1000px;
color: #0D1B1E;
}
body > header {
display: flex;
flex-flow: row nowrap;
margin: 0 auto;
background-color: #FAF9F4;
height: 100%;
}
header{align-items:center;}
.first {
padding: 5px;
flex: 1;
}
.second {
padding: 5px;
flex: 3;
}
.third {
padding: 5px;
flex: 1;
}
<header>
<div class="first">
<img src="images/header-logo1.png" alt="Law Enforcement Badge Logo" width="100" height="100">
</div>
<div class="second">
<h1>On Scene Academy</h1>
<h2>law enforcement training and tactics</h2>
</div>
<div class="third">
<img src="images/header-logo2.png" alt="Law Enforcement Badge Logo" width="100" height="100">
</div>
</header>
Комментарии:
1. Ваш ответ можно было бы улучшить, объяснив, как ваш код устранил проблему. Использование комментариев в коде часто является хорошей идеей, поскольку часто бывает трудно выделить различия в двух блоках кода.
Ответ №2:
Это что-то вроде этого?
* {
box-sizing: border-box;
}
html {
height: 100%;
font: 16px Geneva, Verdana, Helvetica, sans-serif;
}
body {
margin: 0px;
padding: 0px;
max-width: 1000px;
color: #0D1B1E;
}
/** Here is grid container **/
header {
display: grid ;
max-width: 100%;
background: black;
grid-template-columns: 1fr auto 1fr; /** this means 3 columns with first and third columns take up same space after the second column auto adjust in the center. **/
grid-template-rows: 1fr; /* this means 1 row */
}
div.first {
background: grey;
grid-column-start: 1; /* this take the first column */
justify-self: center; /* align inline row axis */
}
div.second {
background: grey;
grid-column-start: 2; /* this takes second column */
align-self: center; /* position at the center of the container.*/
}
div.second h1{
background: white;
padding: 0;
margin: 0;
}
div.second h2{
background: white;
padding: 0;
margin: 0;
}
div.third {
background: grey;
grid-column-start: 3; /* this takes third column */
justify-self: center; /* align inline row axis. */
}
<header>
<div class="first">
<img src="https://i.kinja-img.com/gawker-media/image/upload/s--2m8vKwCk--/c_scale,f_auto,fl_progressive,q_80,w_800/17oyh0zri482jjpg.jpg" alt="Law Enforcement Badge Logo" width="100" height="100">
</div>
<div class="second">
<h1>On Scene Academy</h1>
<h2>law enforcement training and tactics</h2>
</div>
<div class="third">
<img src="https://i.kinja-img.com/gawker-media/image/upload/s--2m8vKwCk--/c_scale,f_auto,fl_progressive,q_80,w_800/17oyh0zri482jjpg.jpg" alt="Law Enforcement Badge Logo" width="100" height="100">
</div>
</header>
Ответ №3:
Это то, что вы ищете:
header {
display: flex;
}
.first,
.second,
.third {
height: 50px;
}
h1,
h2 {
font-weight: normal;
padding: 0;
/*margin: 0;*/
font-size: 12px;
}
<header>
<div class="first">
<img src="https://via.placeholder.com/50" alt="Law Enforcement Badge Logo">
</div>
<div class="second">
<h1>On Scene Academy</h1>
<h2>law enforcement training and tactics</h2>
</div>
<div class="third">
<img src="https://via.placeholder.com/50" alt="Law Enforcement Badge Logo">
</div>
</header>
Вот ссылка на FIDDLE, где вы можете проверить этот код.
Ответ №4:
Ваши изображения являются украшением, а не фактическим содержимым. Я бы посмотрел на их удаление и добавление с помощью элементов psudo.
Редактировать — я перешел с абсолютного позиционирования на использование inline-block
для лучшей обработки вертикального центрирования.
body>header {
margin: 0 auto;
background-color: #FAF9F4;
min-height: 110px;
}
/*Common Stuff for psudo elements*/
body>header::before,
body>header::after {
content: '';
display: inline-block;
vertical-align:middle;
width: 100px;
height: 100px;
margin: 5px;
background-repeat: no-repeat;
background-size: contain;
}
/*Left Image - adjust url as required*/
body>header::before {
background-image: url(https://fillmurray.com/100/100);
}
/*Right Image - adjust url as required*/
body>header::after {
background-image: url(https://fillmurray.com/200/200);
}
/*Adjust margin on h1,h2 as you want less space there*/
body>header> div > h1 {
margin-bottom: 0.1em;
}
body>header> div > h2 {
margin-top: 0.1em;
}
/*Vertically center text*/
.headerContainer {
display:inline-block;
vertical-align:middle;
/*And horizontal center title*/
text-align: center;
/*Limit width*/
width: calc(100% - 240px);
}
* {
box-sizing: border-box;
}
html {
height: 100%;
font: 16px Geneva, Verdana, Helvetica, sans-serif;
}
body {
margin: 0px;
padding: 0px;
max-width: 1000px;
color: #0D1B1E;
}
<header>
<div class="headerContainer">
<h1>On Scene Academy</h1>
<h2>law enforcement training and tactics</h2>
</div>
</header>
Или, если вы хотите придерживаться flex
body>header {
margin: 0 auto;
background-color: #FAF9F4;
min-height: 110px;
display:flex;
flex-flow: row nowrap;
/*Justify content so to elements are spaced "edege to edge"
See: https://css-tricks.com/almanac/properties/j/justify-content/
*/
justify-content: space-between;
/*Center the items in the row
See: https://css-tricks.com/almanac/properties/a/align-items/
*/
align-items:center;
}
/*Common Stuff for psudo elements*/
body>header::before,
body>header::after {
content: '';
flex:1;
width: 100px;
height: 100px;
margin: 5px;
background-repeat: no-repeat;
background-size: contain;
}
/*Left Image - adjust url as required*/
body>header::before {
background-image: url(https://fillmurray.com/100/100);
}
/*Right Image - adjust url as required*/
body>header::after {
background-image: url(https://fillmurray.com/200/200);
/*The itme will grow with flex to set the image to the right*/
background-position-x: right;
}
/*Adjust margin on h1,h2 as you want less space there*/
body>header> div > h1 {
margin-bottom: 0.1em;
}
body>header> div > h2 {
margin-top: 0.1em;
}
.headerContainer {
flex:3;
/*And horizontal center title*/
text-align: center;
}
* {
box-sizing: border-box;
}
html {
height: 100%;
font: 16px Geneva, Verdana, Helvetica, sans-serif;
}
body {
margin: 0px;
padding: 0px;
max-width: 1000px;
color: #0D1B1E;
}
<header>
<div class="headerContainer">
<h1>On Scene Academy</h1>
<h2>law enforcement training and tactics</h2>
</div>
</header>
Или вы можете создать с его помощью сетку. Который имеет самый простой HTML из всех
body>header {
margin: 0 auto;
background-color: #FAF9F4;
/*USe CSs Grid*/
display: grid;
/*3 Columns, 110px for each image, 1fr = remaining space*/
grid-template-columns: 110px 1fr 110px;
/*Two Rows*/
grid-template-rows: 1fr 1fr;
/*Min height is the size of the images a little padding*/
min-height: 110px;
}
/*Common Stuff for psudo elements*/
body>header::before,
body>header::after {
content: '';
width: 100px;
margin: 5px;
/*Our "bookend" images span 2 rows*/
grid-row-start:span 2;
background-repeat: no-repeat;
background-size: contain;
/*Center the image*/
background-position-y: center;
}
/*Left Image - adjust url as required*/
body>header::before {
background-image: url(https://fillmurray.com/100/100);
/*Start at the 1st column for the left image*/
grid-column-start:1;
}
/*Right Image - adjust url as required*/
body>header::after {
background-image: url(https://fillmurray.com/200/200);
/*start at the last colum for the right image*/
grid-column-start:3;
}
/*Center the header text and adjust the margins*/
h1,h2 {
text-align:center;
margin:0.125em;
align-self: center;
}
header h1{
/*Close up the spacing on the h1*/
/*align-self: end;*/
}
/*POsition the h2 */
header h2 {
/*On the second row*/
grid-row-start:2;
/*Starting at the 2nd colum*/
grid-column-start:2;
}
* {
box-sizing: border-box;
}
html {
height: 100%;
font: 16px Geneva, Verdana, Helvetica, sans-serif;
}
body {
margin: 0px;
padding: 0px;
max-width: 1000px;
color: #0D1B1E;
}
<header>
<h1>On Scene Academy</h1>
<h2>law enforcement training and tactics</h2>
</header>
Ответ №5:
Я нашел гораздо более простой и менее трудоемкий способ добиться этого с помощью кода. Вот что я сделал:
body {
margin: 0px;
padding: 0px;
}
header {
display: flex;
flex-flow: row nowrap;
justify-content: center;
align-items: center;
background-color: aquamarine
}
h1 {
font-size: 40px;
margin: 0px;
text-align: center;
}
h2 {
font-size: 20px;
margin: 0px;
padding-bottom: 10px;
text-align: center;
}
img {
margin: 10px 15px;
}
<html>
<body>
<header>
<img src="header-logo1.png" alt="#" width="100" height="100">
<div>
<h1>On Scene Academy</h1>
<h2>law enforcement training and tactics</h2>
</div>
<img src="header-logo2.png" alt="#" width="100" height="100">
</header>
</body>
</html>