媒体查询以在flexbox中进行文本对齐

时间:2019-03-01 09:53:00

标签: html css html5 css3 flexbox

当屏幕尺寸减小时,在媒体查询下,我有两个并排的flexbox并排堆叠。左框的文本左对齐,右框的文本右对齐。激活媒体查询后,是否可以使两个弹性框中的文本居中对齐?如果可以的话,请发布代码。谢谢。

/* Container for flexboxes */
header {
  display: -webkit-flex;
  display: flex;
}

/* Responsive layout - makes the menu and the content (inside the section) sit on top of each other instead of next to each other */
@media (max-width: 600px) {
  header {
    -webkit-flex-direction: column;
    flex-direction: column;
  }
}


/* Style the side */
logosmall {
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  background: #FA8072;
  padding: 20px;
}

/* Style the content */
bannersmall {
  -webkit-flex: 3;
  -ms-flex: 3;
  flex: 3;
  background-color: #FFA07A;
  padding: 10px;
}


/* Container for flexboxes */
section {
  display: -webkit-flex;
  display: flex;
}
<header>

<logosmall>
<h1 style="font-size:15px; font-style:italic; color:#555; text-align: left;">Text-align: left</h1>
</logosmall>

<bannersmall>
<h1 style="font-size:15px; font-style:italic; color:#555; text-align: right;">Text-align: right</h1>
</bannersmall>
</header>

2 个答案:

答案 0 :(得分:1)

您需要删除这两个元素的内联样式以实现文本对齐,而应将它们放入CSS文件中。然后,您只需将text-align:center;样式添加到现有的媒体查询中即可。

 @media (max-width: 600px) {
    header {
      -webkit-flex-direction: column;
      flex-direction: column;
      text-align:center;
    }
    logosmall, bannersmall {
      text-align:center;
    }
}

logosmall {
  text-align:left;
}

bannersmall {
  text-align:right;
}

答案 1 :(得分:1)

删除h1上的内联样式,这是更新的代码。希望对您有帮助

/* Container for flexboxes */
header {
  display: -webkit-flex;
  display: flex;
}

/* Responsive layout - makes the menu and the content (inside the section) sit on top of each other instead of next to each other */


/* Style the side */
logosmall {
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  background: #FA8072;
  padding: 20px;
}
header h1{
font-size:15px; font-style:italic; color:#555; text-align: left;
}
header bannersmall h1{
  text-align:right;
}
/* Style the content */
bannersmall {
  -webkit-flex: 3;
  -ms-flex: 3;
  flex: 3;
  background-color: #FFA07A;
  padding: 10px;
}


/* Container for flexboxes */
section {
  display: -webkit-flex;
  display: flex;
}

@media (max-width: 600px) {
  header {
    -webkit-flex-direction: column;
    flex-direction: column;
  }
  header h1, header bannersmall h1{
  text-align:center;
  }
}
<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content ="ie=edge">




<title>Test</title>

<style>

</style>
</head>



<body>

<header>

<logosmall>
<h1>Text-align: left</h1>
</logosmall>

<bannersmall>
<h1>Text-align: right</h1>
</bannersmall>
</header>

</body>