Learn CSS Grid “The Easy Way”!

Category Image 052

CSS Grid is a layout system for the web, allowing developers to create complex, responsive designs using rows and columns. Grid is used to make complex web design layouts more easily. In this article, we will explore the basics of CSS Grid with a step-by-step guide. Readers will discover how to create complex, responsive web designs using rows and columns with CSS Grid.

First things first, we have to make a div and give it a class of containers or anything you want.

CSS Basics: Visibility: Hidden vs. Display: None

Category Image 052

visibility: hidden and display: none are two CSS properties that can be used to hide elements. While they may seem similar at first glance, there are some significant differences between them. In this article, we’ll explore these differences and provide some examples to illustrate their use.

The UX Designer Toolbox

Unlimited Downloads: 500,000+ Wireframe & UX Templates, UI Kits & Design Assets Starting at only $16.50 per month!

 

visibility: hidden

The visibility property in CSS determines whether or not an element is visible on the web page. If set to hidden, the element will be hidden from view, but it will still occupy space on the page. This means that any other elements that would normally be positioned after it will still be positioned as if the hidden element were still visible.

Here’s an example of how visibility: hidden works:

<!DOCTYPE html>
<html>
  <head>
    <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cstyle%3E%0A%20%20%20%20%20%20%23hidden-element%20%7B%0A%20%20%20%20%20%20%20%20visibility%3A%20hidden%3B%0A%20%20%20%20%20%20%7D%0A%20%20%20%20%3C%2Fstyle%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;style&gt;" title="&lt;style&gt;" />
  </head>
  <body>
    <p>This is some text before the hidden element.</p>
    <div id="hidden-element">
      <p>This element is hidden using visibility.</p>
    </div>
    <p>This is some text after the hidden element.</p>
  </body>
</html>

In this example, the #hidden-element is hidden using visibility: hidden. Notice that the element still occupies space on the page, and the text after it is still positioned as if it were visible.

display: none

The display property in CSS determines how an element is displayed on the web page. If set to none, the element will be completely removed from the page and will not occupy any space. This means that any other elements that would normally be positioned after it will be repositioned as if the hidden element were not present.

Here’s an example of how display: none works:

<!DOCTYPE html>
<html>
  <head>
    <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cstyle%3E%0A%20%20%20%20%20%20%23hidden-element%20%7B%0A%20%20%20%20%20%20%20%20display%3A%20none%3B%0A%20%20%20%20%20%20%7D%0A%20%20%20%20%3C%2Fstyle%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;style&gt;" title="&lt;style&gt;" />
  </head>
  <body>
    <p>This is some text before the hidden element.</p>
    <div id="hidden-element">
      <p>This element is hidden using display.</p>
    </div>
    <p>This is some text after the hidden element.</p>
  </body>
</html>

In this example, the #hidden-element is hidden using display: none. Notice that the element does not occupy any space on the page, and the text after it is repositioned as if the element were not present.

When to use visibility: hidden vs. display: none

Now that we’ve seen how visibility: hidden and display: none work, it’s important to consider when to use one over the other.

Use visibility: hidden when you want to hide an element from view but still want it to occupy space on the page. This can be useful when you want to reveal the element later or when you want to maintain the layout of the page.

Use display: none when you want to completely remove an element from the page and don’t want it to occupy any space. This can be useful when you want to completely hide an element and don’t plan to reveal it later.

Chris’ Corner: Resizing, Conditionals, and Initials

Category Image 052

Ahmad Shadeed recently wrote:

I like to think of CSS as a conditional design language.

It totally is! We tend to think of stuff like @media queries as the conditional part:

@media (max-width: 550px) {
  .grid {
    grid-template-columns: 1fr;
  }
}

That’s true, and new stuff like container and style queries are giving us more “conditional” stuff to work with. But it might be better to think of literally everything in CSS as conditional. Every selector you can write is conditional in some way. Just a sector like aside is conditional — it says, only style elements that match that selector. To grok CSS, you are grokking a massive set of conditions. As Ahmad indicated:

.alert p:empty {
  display: none;
}

This is a big logical if statement. IF the element is a paragraph. IF that paragraph is empty. IF it is a child of another element with a class of alert. All those IFs have to be true for the styles to apply.


You could take conditional CSS another step up though, meaning conditions by which to load the entire .css file at all.

Vadim Makeev wrote up some interesting experiments around all this. Say you do:

<link rel="stylesheet" href="style.css" media="print">

The browser is smart enough not to load that CSS file at all (unless you’re printing, natch).

You can also do this:

<link rel="stylesheet" href="base.css">
<link rel="stylesheet" href="mobile.css"
  media="(max-width: 767px)"
>

Butttttt, the browser will actually load both of those files regardless if the media matches or not. So no obvious immediate benefit, but that’s where Vadim’s research comes in. While all the files with non-matching media (queries) still load, the browser is smart enough to make the non-matching stylesheets load with a lower priority. At least in Chrome and Firefox — Safari has some bug that makes the priority levels not provide the perf benefits.

Pretty cool I think. Doing this kind of work by hand feels onerous though, I’d love to see build processes deal with it automatically.


Ya know I was scared for Mozilla & Firefox for a while. Those big layoffs in 2020 included many browser engine engineers and it seemed like it would be hard to continue to be a viable browser engine alternative without a strong team there. But I was essentially wrong. Since then they’ve shipped plenty of important web platform features at a decent pace, including the ever-important Container Queries and new color formats. Putting MDN on GitHub happened after the layoffs too and that seems like a massive thing to get shipped.

Last year WIRED asked Is Firefox OK? There wasn’t really an answer there, but some good information. We know Google provides the bulk of their income, but they showed really strong growth with their own products and services, saying 14% of all revenue was that back in 2021. They’ve clearly been trying new stuff to increase that, so things look on the right track to me.

I like to see little stories like this: Mozilla fixed an 18-year old CSS bug in the Firefox browser. So they aren’t just playing catch up, they are getting details right along the way too. Better late than never. This one was a weird bug with ::first-letter, the real ticket for doing drop caps:

They said it was kind of a bandaid for now but still cool. Speaking of drop caps though… ::first-letter was always fraught for this purpose. Much better would be to support initial-letter. C’mon Firefox, you can do it!


Michelle Barker on Resizing with CSS:

One drawback is the resize control is only positioned in the bottom right corner of the element, and it’s not possible to style it. It would be nice to have this customiseable ability, and increase the area of the resize control.

Yes!

That’s literally my opening thing in Things CSS Could Still Use Heading Into 2023. Just imagine the CodePen editors. So many things resize, and the ability to do that in HTML and CSS alone would be super sweet. But probably with JavaScript callbacks so we can do stuff like save/persist what has changed in the UI.

And ya know, that makes me think about how we only just got a scrollend event in JavaScript, maybe we should get a resizeend event too.

How To Use CSS To Maintain Aspect Ratio For Responsive Design

Category Image 052

Maintaining the Aspect ratio of a div is a common requirement when creating responsive web designs. In this article, we’ll explore how to use CSS to maintain the Aspect ratio of a div as the window’s width changes.

To achieve this, we’ll use the padding hack. The padding hack is a technique that uses a percentage value for padding-top or padding-bottom to maintain the Aspect ratio of an element. The percentage value is calculated based on the width of the parent element. As the width of the parent element changes, the padding value will adjust to maintain the Aspect ratio of the child element.

Your Web Designer Toolbox
Unlimited Downloads: 500,000+ Web Templates, Icon Sets, Themes & Design Assets


 

Let’s start by creating a div element with a background color.

<div class="aspect-ratio"></div>

<style>
  .aspect-ratio {
    background-color: #ccc;
  }
</style>

To maintain the Aspect ratio of this div, we’ll set its padding-top to a percentage value. The percentage value will be calculated based on the desired Aspect ratio of the div. For example, if we want the Aspect ratio to be 16:9, we’ll set the padding-top to 56.25% (9/16 * 100).

.aspect-ratio {
  background-color: #ccc;
  padding-top: 56.25%;
}

Now, as the width of the parent element changes, the padding value will adjust as desired.

Here’s an example that shows how to use the padding hack on a div with a background image.

<div class="aspect-ratio" style="background-image: url('image.jpg')"></div>

<style>
  .aspect-ratio {
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    position: relative;
  }
  
  .aspect-ratio:before {
    content: "";
    display: block;
    padding-top: 56.25%;
  }
  
  .aspect-ratio > * {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
</style>

In this example, we are again using the padding hack, and we’re also using a pseudo-element (:before) to create the padding. We’re setting the position of the parent element to relative and the position of the child element to absolute to position the child element inside the parent element. We’re also setting the width and height of the child element to 100% to fill the parent element.

In conclusion, the padding hack is a simple and effective technique for maintaining the Aspect ratio of a div as the window’s width changes. By using a percentage value for padding-top or padding-bottom, we can calculate the padding value based on the desired Aspect ratio of the div. This technique is widely used in responsive web design and can be used to create a variety of layouts and designs. Be sure to check out our library of CSS articles and tutorials while you’re here!

How To Align Checkboxes and Their Labels Consistently Across Browsers

Category Image 052

While checkboxes are relatively straightforward to implement, aligning them with their labels can be a challenge, as each browser renders them differently. In this article, we will explain how to align checkboxes and their labels consistently across all browsers using CSS.

UNLIMITED DOWNLOADS: 500,000+ WordPress & Design Assets

Sign up for Envato Elements and get unlimited downloads starting at only $16.50 per month!

 

Wrap the Checkbox and Label in a Container

The first step is to wrap the elements in a container so we can use it to apply styling to both the checkbox and the label.

<div class="checkbox-container">
  <input type="checkbox" id="checkbox1">
  <label for="checkbox1">Checkbox Label</label>
</div>

Style the Checkbox and Label

Once we have our container, we can use CSS to position the checkbox and label, adjust their size, and style them.

.checkbox-container {
  display: flex;
  align-items: center;
}

.checkbox-container input[type="checkbox"] {
  margin-right: 10px;
}

.checkbox-container label {
  margin: 0;
}

The display: flex; property allows us to align the checkbox and label vertically. The align-items: center; property centers the checkbox and label vertically within the container.

The margin-right: 10px; property adds a small amount of space between the checkbox and the label. The margin: 0; property removes any margin that may be added by default by the browser.

Styling the Checkbox to make it visually appealing

In addition to aligning the checkbox and label, we can also style the checkbox to make it more visually appealing.

.checkbox-container input[type="checkbox"] {
  appearance: none;
  width: 20px;
  height: 20px;
  border: 2px solid #ccc;
  border-radius: 4px;
  background-color: #fff;
  cursor: pointer;
}

.checkbox-container input[type="checkbox"]:checked {
  background-color: #007bff;
  border-color: #007bff;
}

.checkbox-container input[type="checkbox"]:checked::before {
  content: "\2713";
  font-size: 16px;
  color: #fff;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

The appearance: none; property removes the default styling of the checkbox, allowing us to create our own custom style. The width and height properties set the size of the checkbox. The border property creates a border around the checkbox, and the border-radius property rounds the corners of the checkbox.

The background-color property sets the background color of the checkbox, and the cursor: pointer; property changes the cursor to a pointer when the user hovers over the checkbox.

The input[type="checkbox"]:checked selector styles the checkbox when it is checked. The background-color property changes the background color of the checkbox, and the border-color property changes the color of the border.

The input[type="checkbox"]:checked::before pseudo-element adds a checkmark to the checkbox when it is checked. The content property adds the checkmark character, and the font-size property sets the size of the checkmark. The color property sets the color of the checkmark, and the position: absolute; property positions the checkmark in the center of the checkbox.

Conclusion

By wrapping checkboxes and their labels in a container and applying CSS styling, we can align checkboxes and their labels consistently across all browsers, as well as create a more visually appealing and user-friendly form element. Be sure to check out our other CSS articles while you’re here!

Chris’ Corner: More Like Hypography

Category Image 052

CSS hyphenation support is pretty good — just a -webkit- prefix left for Safari I’d love to see them yank off. Toss it on a parent, let it cascade, and you’ll see text hug the ragged edge a little closer and a little more consistently. You don’t have to use it, it’s a bit of an aesthetic choice.

I was thinking about this because I saw Hyphenopoly.js — a polyfill for hyphenation in JavaScript that’s come out in the last few months. I kinda don’t get it with the browser support being so good, but it does work in Node which might be interesting, and I suppose this would be extensible to written languages where hyphenation isn’t supported yet.

Update from Mathias Nater:

Hyphenopoly.js came out 2018 and its predecessor – Hyphenator.js –  around 2008, some time before hyphens:auto; was available.
There are still many languages that are not supported natively in all browsers.

Hyphenopoly.js supports 72 languages and, yep, it is extensible: we’ll just need hyphenation patterns (the same patterns TeX uses) or a huge list of pre-hyphenated words where I can compute the patterns from.

(I was under the impression it had just come out in the last few months!)

There is a ton more to the CSS art of controlling where words break through. One of the most comprehensive reads on the subject is Will Boyd’s Deep Dive into Text Wrapping and Word Breaking.

Pen

While we’re on type for a second, I do need you to know that Stabby exists:


More good news (in a sec). You know how the content of a page can shift around when a custom font loads after a fallback font has rendered? This is one of the great tradeoffs of display websites right now. Delay rendering until the custom font is ready means no layout shift (good!), but then you’re… delaying rendering (bad!). To my great surprise, the web has shifted toward not delaying rendering, largely thanks to CSS’ font-display: swap;

It is possible to have your cake and eat it too have non-shifting custom font loading without delayed rendering through CSS trickery. It involves using a font loader so that you know when the custom font loads and can adjust CSS to make sure none/little layout shift happens. The tricks were adjusting things like font-size, letter-spacing, and those classics.

The good news is that that old slightly hacky way of dealing with font fallbacks is out and a new school way of dealing with font fallbacks is in. Here’s Katie Hempenius’ recent article:

This article is a deep dive into font fallbacks and the size-adjustascent-overridedescent-override, and line-gap-override APIs. These APIs make it possible to use local fonts to create fallback font faces that closely or exactly match the dimensions of a web font. This reduces or eliminates layout shifts caused by font swapping.

Improved font fallbacks

Four new things just for fallbacks! Wow. Say you’re loading a custom font called Poppins, it ends up looking like this:

body {
  font-family: Poppins, "fallback for poppins";
}

@font-face {
  font-family: "fallback for poppins";
  src: local("Times New Roman");
  ascent-override: 105%;
  descent-override: 35%;
  line-gap-override: 10%;
}

My brain immediately went uhmmmmm wouldn’t these metrics totally depend on the combination of the custom font and the fallback font? Apparently not though!

Because font metric overrides are calculated using measurements that come from the metadata of the web font (and not the fallback font), they stay the same regardless of which font is used as the fallback font.

That’s really great. So you can basically figure out (or look up) the overrides for your custom font, put them in place, and you’re straight up good to go. That’s a good API.


Welp I didn’t really intend for this whole issue to be about typography stuff, but here we are. You gotta see Adam Argyle’s Text Replace Transitions!

You could code any number of ways. But Adam did it using the new View Transitions API (so you’ll only be able to see the demo in Chrome Canary). It’s such a fun way to play with animating things because the API is so tidy: call document.startViewTransition, change the DOM, let it animate (control with CSS if you want). Hopefully, the CSS properties will be all that is needed entirely from cross-page View Transitions (I think that’s the case, I just haven’t seen it really work well yet).

Chris’ Corner: Gradients, Generators, and Glows

Category Image 052

Radial gradients do represent a bit of a leap up in complexity compared to linear gradients in CSS. With linear gradients, you sorta pick a direction and plop some stops on there. The default direction, to bottom, you don’t even have to include if that’s the direction you want, and two color stops with no additional values just mean “all the way at the top to all the way at the bottom”. Something like this linear-gradient(darkblue, blue).

Good news: radial gradients do maintain making most parameters optional, so radial-gradient(darkblue, blue) is still functional and half-decently-useful. But the complexity goes up from there.

  • Radial gradients need to be told to behave like a circle if that’s the shape you want, not the default ellipse.
  • You can tell a radial gradient where to stop, before you even get to the color stops.
  • You can choose a starting position for the radial gradient, it doesn’t have to be dead center.
  • There are keywords that tell radial gradients to extend to certain relevant points of the container, like closest-side and furthest-corner and such.

It was enough for Patrick Brosset to ask Do you really understand CSS radial-gradients?, which, ya know, fair.

human eyes drawn with css radial gradients.

There is no built-in way to generate a random number in CSS. Maybe there should be, as there are countless demos that use some other technology to feed random numbers into CSS. The use case is often generative art or decorative effects, but there is so much of that and the results can be so cool, it’s almost shame we don’t have it. So what do we do to get random numbers in CSS?

  • We use the random function in a CSS processor (e.g. random() works in Sass) — but then it’s only random at build time.
  • We use a random number created in JavaScript, then set a --custom-property with it. Maybe even Houdini.
  • We use user input somehow to make a value feel random.

Kacper Kula’s Randomness in CSS kinda gets into all three of those. He uses a hand-built random number generator in Sass based on prime numbers. The @property syntax is used to ensure a custom property is an integer and is sometimes used as a seed that comes in via JavaScript.

Demo Pen

Let me leave you this week with just a tiny classy snippet of CSS from CodyHouse:

.component {
  /* inner glow 👇 */
  box-shadow: 
    inset 0 0 0.5px 1px hsla(0, 0%, 100%, 0.075),

  /* shadow ring 👇 */
    0 0 0 1px hsla(0, 0%, 0%, 0.05),

  /* multiple soft shadows 👇 */
    0 0.3px 0.4px hsla(0, 0%, 0%, 0.02),
    0 0.9px 1.5px hsla(0, 0%, 0%, 0.045),
    0 3.5px 6px hsla(0, 0%, 0%, 0.09);
}
Demo Pen

That’s just a nice look right there.

The Difference Between the :where() and :is() CSS Selectors

Category Image 052

The CSS selectors :where() and :is() are two pseudo-classes that allow you to select elements based on their relationship with other elements. Although they sound similar, they are different in terms of functionality and syntax.

Your Web Designer Toolbox
Unlimited Downloads: 500,000+ Web Templates, Icon Sets, Themes & Design Assets


The :where() pseudo-class was introduced as part of the CSS Selectors Level 4 specification and allows you to select elements based on the presence of other elements that match a specific condition. In other words, you can select elements based on the relationship between elements in a DOM tree. For example, you can use the :where() selector to select a list item li only if it is the first child of an unordered list ul:

li:where(:first-child of ul) {
  background-color: yellow;
}

On the other hand, the :is() pseudo-class is part of the CSS Selectors Level 3 specification and allows you to select an element if it is one of several different selectors. It is similar to the logical OR operator, in CSS. For example, you can use the :is() selector to select a p element if it is either the first child of its parent or has a class of highlight:

p:is(:first-child, .highlight) {
  background-color: yellow;
}

It’s important to note that the :where() selector has better browser support than the :is() selector, and that the :is() selector should not be used in conjunction with the :not() pseudo-class.

Chris’ Corner: Font Size, Document Hierarchy, and Dialog

Category Image 052

How about some accessibility quick hits!


It’s a bit hard to keep track of when using certain CSS value types is bad. For a while, using pixel (px) values in media queries was considered a bad practice as the breakpoints didn’t trigger as expected when a user zoomed in. But then that changed, and media queries do now, and using pixels for media queries isn’t really a bad practice any more.

But is using px still a bad practice in other cases? Yes, says Josh Collingsworth.

… when or if the user changes their preferred font size, if you’re using em and rem, all the text on your website will change accordingly, like it should. 2rem is still double that font size; 0.5rem is still half of it.

By contrast, px values are static20px is just 20px, regardless of the container’s, browser’s, or user’s font size. No matter how large or small the user’s font preference may be, when you set a value in static pixels, it clobbers that choice and overrides it with the exact value you specified.

Critically, that means if your stylesheet uses px to set font-size anywhere in it, any and all text based on that value will be impossible for the user to change.


Did you know that it was, up until fairly recently, specced that heading elements (e.g. <h1>, <h2>, etc) would “reset” inside of a new <section> (and similar) elements? I admit I thought that was kind of a neat idea. For example, if you’re building a site with HTML partials, and one of those as a little <aside> that I plunked into a sidebar or something, that I could have an isolated set of headings that would be valid and squoosh into the proper hierarchy going on on the rest of the page, without knowing or caring about headers scattered around the rest of the page.

Well, despite being specced, and despite general liking of that idea, no browser ever implemented it, and it was removed from the spec. Pour one out for the Document Outline Algorithm.

Doesn’t make me want to hold my breath for browsers implementing a tab order fixer-upper that follows the visual order of grid or flex items, like has been tossed around a bit.


Léonie Watson:

… you may be surprised to learn that there is no way for authors to design the aural presentation of web content, in the way they can design the visual presentation.

Why we need CSS Speech

All the major browsers now have “listening” features built right into them, and still no way to control that experience.

The good news is that there is a spec for CSS speech. Léonie thinks it’s too old and too big, so offered to take it on and trim it down (hopefully into something browsers will take on). Looks like that’s starting to happen based on the names on the spec.


This is a wild story: Safari’s date-picker is the cause of 1/3 of our customer support issues.

Shortly after I read it, I had to use this exact date picker a number of times while filling out online forms on an iPad at a doctor office and I friggin get it. Using that date picker for birthdays is horrible. Even knowing exactly how to do it, I tripped up several times in a row.

The danger of all this is companies, sometimes rightfully, going “screw it we’ll just build our own”, and having that home-grown picker perhaps solve this one UX issue, but cause accessibility issues that harm another group of people.


A smidge of good news. We can Use the dialog element (reasonably) says Scott O’Hara. There have been some recent updates that solve some the focus handling issues that apparently gave it a red flag before. I’m glad about this, as I think it suffers from exactly what I described above: people build dialogs in-house instead and get some (if not most) of the accessibility requirements wrong. Focus-trapping alone is brutally difficult to get right, and it’s just a freebie with <dialog>.

A Guide to CSS Color Functions

Category Image 035

Hey, there fellow developers! Today, we’re going to dive into the world of CSS color functions.

You might have used CSS to change the color of an element on a web page, but have you ever heard of CSS color functions? If not, tighten your seat belts because you’re about to learn something new and super useful!

The Ultimate Guide What To Look Out for in Web Hosting

Category Image 052

Web hosting is a service that allows individuals and organizations to make their websites accessible on the internet. When you create a website, you need a place to store all of your website's files, such as HTML, CSS, and images. Web hosting companies provide servers, which are powerful computers that are connected to the internet, where you can store and run your website's files.

When you sign up for a web hosting service, you are essentially renting space on a server to host your website. Depending on the type of web hosting plan you choose, you may have access to a range of features and resources, including disk space, bandwidth, email accounts, and databases.

Quick Tip: How To Disable Resizing of a Textarea in HTML or CSS

Category Image 052

In this quick tip, we’re going to show you 2 different ways to disable the resizing of a textarea, for those times when you don’t want the user to be able to control it in this manner. It’s a relatively quick process, with just some simple CSS using the resize CSS property.

Your Designer Toolbox Unlimited Downloads: 500,000+ Web Templates, Icon Sets, Themes & Design Assets

 

HTML

The HTML textarea element provides a resizable property by default. To disable it, you can use the CSS property resize: none in the textarea element. Here is an example:

 <textarea style="resize: none;"></textarea> 

CSS

You can also disable the resizable property of a textarea by using CSS that is not inline. You can add a class to the textarea element and then add the CSS property resize: none to the class. Here is an example:

<textarea class="no-resize"></textarea>

<style>
  .no-resize {
    resize: none;
  }
</style>

Beginner’s Guide: How to Center Align a Video in WordPress

Category Image 091

Do you want to center-align a video in WordPress?

By default, if your video’s width is less than your article area, then WordPress automatically aligns it to the left, leaving extra white space on the right side.

In this article, we will show you how to easily center align a video in WordPress.

How to center align a video in WordPress

Why Center Align Videos in WordPress?

When you embed a video in WordPress, it automatically aligns them to the left by default. This is because videos are external content embedded in the content, so WordPress is unable to guess how you would like to display it.

As a best practice, it automatically aligns it to the left, leaving it up to you to adjust the alignment if needed.

By aligning the video to the center, users will have a better experience viewing your content. This way, you won’t have noticeable blank space on the one side of the page, which could give an unprofessional look.

Besides, if you upload videos directly to WordPress, the same thing will happen to them if their width is less than your content area. WordPress will align them to the left by default.

That being said, let’s see how you can easily center-align a video in a WordPress website. We’ll cover both the block editor and classic editor, so you can click the links below to jump ahead to any section.

How to Center Align Video in WordPress Content Editor

If you want your video to fill the width of your content area, then the best way to do this is by adding a YouTube or Vimeo video URL directly in the WordPress content editor.

First, you’ll need to edit a post or a page or add a new one. Once you are in the content editor, simply paste the link to the video. WordPress will embed the video automatically.

Paste video embed code in block editor

Next, select the video block and then click the Change Alignment option. From the dropdown menu, you can choose the position of the video.

WordPress lets you choose from the following alignments:

  • wide width
  • full width
  • align left
  • align center
  • align right.

Go ahead and select the ‘Align center’ option.

Align the video to the center

After that, you can preview and publish your page or post.

The video will now be center-aligned.

Center aligned video preview

However, sometimes for one reason or another, you may need to use the embed code. In that case, you will need to add some simple HTML around your video’s embed code.

First, you need to click the 3 dotted icons in the video block. After that, you can select the ‘Edit as HTML’ option from the dropdown menu.

Edit as HTML

Next, you can enter the following piece of HTML code around the embed code of the video:

<div style="text-align:center;">

/// your video embed code goes here

</div>

Here’s what your embed code would look like with the custom HTML.

Preview of custom HTML code

You can now save your changes and preview the post or page. Your video will be neatly aligned in the center of your content area.

Another approach is to manually increase your video’s width to fit the content area. To achieve this, you need to add or change the ‘width’ parameter in your embed code.

<iframe width="760" height="315" src="https://www.youtube.com/embed/4YpyiJ05YOg" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

How to Center Align Video in the Classic Editor

If you’re using the Classic editor, then you can center align videos by editing a post or creating a new one.

Once you’re in the editor, switch to the Text view. Now enter the following HTML code:

<div style="text-align:center;">

/// your video embed code goes here

</div>

Just make sure to replace ‘your video embed code goes here’ with your video’s embed code.

Once that’s done, it will look something like this:

Center align videos in classic editor

You can now preview and publish your page.

Simply visit your website to see the center-aligned video.

Center aligned video classic editor preview

We hope this article helped you learn how to center align a video in WordPress. You may also want to see our guide on how to start a WordPress blog and must-have WordPress plugins.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

The post Beginner’s Guide: How to Center Align a Video in WordPress first appeared on WPBeginner.

How To Build A Magazine Layout With CSS Grid Areas

Category Image 052

In this article, I want to talk about the amazing possibilities of a CSS grid and how it allows for complex layouts that are closer to a print design. The design we’ll discuss is actually one I got to work on for a client (modified slightly to a demo case). It will cover two big use cases of a CSS grid:

  1. Having a static grid where we define the specified start and end points for each element;
  2. Using CSS grid template areas to reorder a simple HTML layout easily without updating the HTML.

As a bonus, we will also touch on object-fit and aspect-ratio, which come in handy as well.

Here you can see the design we will be implementing: desktop on the left and a cropped version for mobile on the right (imagine the mobile view to continue with sections 3 and 4). There is quite a lot going on here, and nothing really fits into neat rows and columns. The images are laid out on an uneven grid, sometimes even overlapping, and we have some narrow text and a numbering element that double as a design element.

Artisanal Image Layouts

Let us first look at the image grid elements inside each colored component. While we have four colored components, there are only two variants that get repeated. For easier comparison, I have cut the desktop version in half and put the two halves next to one another — this makes it easier to compare. As you can see, the first and third are the same, as are the second and fourth. If we compare just the first and second variants, they differ, but the basic building blocks are very similar (a full-sized background color, a big image block, a column with a number, and some text). Due to this, we can consider it the same component, just with two alternatives.

In the olden days, we would have had to do the image grid in Photoshop and then add it as one image to the page. Obviously, we could still do this, but that solution has never been particularly good for responsive websites, and using the picture element would work, but we would have to do several layouts in Photoshop and redo everything if we want to change a picture. We would need to do this every time this element gets added with different pictures.

But we wouldn’t be at this part in this article if there wasn’t an alternative! For a while now, it has been safe to use CSS grid, and it is able to solve this layout quite neatly with only a few lines of CSS.

CSS Grid allows us to define a formal grid definition — columns and rows — on the parent element and specify for the children where they should go within the grid. We also get the same justify and align capabilities that flex offers. This removes a lot of the need for wrapping divs and also makes the CSS slimmer.

One thing to note: As a result, your graphical layout can be different from the document structure in HTML.

Screen readers will still rely on the HTML structure, though, so put the most important information first and try to keep everything in a sensible order.

Now let’s get to our images. What is it that we need at a minimum? A container for the images and the images themselves. And you know what? With CSS Grid, that is actually enough — say goodbye to five layers of wrapping divs!

<div class="grid image-grid-3-m4">
   <img class="image-0 " src="" /> 
   <img class="image-1 " src="" />
   <img class="image-2 " src="" />
   <img class="image-3 " src="" />
</div>

A bit more on the markup. To make the styling easier, I added an index to each image (since we want to re-use them, it has to be a class, not an ID) and two classes on the surrounding div, which we will use to define the base styling: a grid utility class and a second one used for identifying the variant. For the variant with three images on the left and a fourth on the right in desktop view, I spent some time thinking about how to best solve the fourth image’s problem: do we add it to the container with the other images and try and move it to the other side, or do we move it on mobile, and so on. In the end, I decided to add the fourth image in the container for the images but hide it on the desktop via CSS and have a separate div in a second location with the same image for displaying in the desktop version. Using display:none will also hide that version from screen readers.

Now that we have the basic HTML and our images in place, it is time to focus on the CSS. If you are completely new to a CSS grid, this helpful article goes into the full syntax and explains it in detail. Unfortunately, I cannot describe the full syntax in this article.

First off, we need to define our grid. Since I had a design to work with, I used a tool that allowed me to put lines on top of the image, position one line at each edge of the image, and see the pixel dimensions in between. It would have been great if the designer had already used a formal grid and told me about it, but unfortunately, that was not the case, so I used the proportionate dimensions as an approximation of what I should use in the grid. Basically, I asked myself what the smallest common divisible number was for each — with some wiggle room — and used that. (Welcome to math class.) My goal was to have the same size for all grid columns and rows while being flexible on the number of columns or rows.

With this method, I determined that I wanted to have 14 columns on mobile and 7 rows plus some uniform gaps. This allowed me to approximate the distribution in the layout while keeping the Aspect ratios close to what they had envisioned. Based on that, we get the following CSS:

.grid {
  display: grid;
}

.image-grid-3-m4 {
  grid-template-rows: repeat(7, 1fr);
  grid-template-columns: repeat(14, 1fr);
    gap: 0.5rem;
}

With these four lines of CSS, we have a grid that is ready to be filled. If you follow along, you will notice that the images are now filling one grid cell each in the first row. This is the automatic layout mechanism that the browser uses, and depending on what you want to do, it can be ideal for defining an evenly laid-out design in seconds.

What is the minimum HTML for that? Again we do not need a lot of extras; a surrounding div and then one for each part is all that we need:

<div class="container">
  <div class="images"></div>
  <div class="numbering"></div>
  <div class="text"></div>
  <div class="single-image"></div>
</div>

For our example, all areas have a class name that identifies what they will hold later. If we look at the mobile layout, though, the number is on top of the images! The cool thing about a CSS grid is that you can layer elements. We already used that for the images above. As you can see, two of them overlap, and we can also do that for whole areas. The layering will be controlled by our old friend, the z-index. Same rules as always: the higher z-index wins and comes to the front.

With that in mind, let’s create two areas: one at the top with the images filling the area and the number as a top layer with most of it transparent to show the images, and the second area below for the text. We could use the grid columns and rows syntax we used earlier, but in this case, we can make our lives even easier with grid-template-areas. With this, you can add names to parts of your grid and then decide for each element which grid area it should appear in. Especially for the page or component frame, this is a much easier and faster way to work and be able to read it all again later than using all of the non-descript numbers.

I think this will be easier to understand with an example.

.container {  
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: repeat(2, 1fr);
  gap: 1.2rem;
  grid-auto-flow: row;
  grid-template-areas:
    "numerology"
    "text";
}

.images { grid-area: numerology; }

.numbering { grid-area: numerology; }

.text { grid-area: text; }
.single-image {display:none}

We define the container as a grid once again, add two rows to it, and then use ‘grid-template-areas’ to give these rows a name. The syntax for this is very unusual for CSS, but it gives you a mini-view of your layout: Numerology is the name of the cell in the first row and Text in the second.

With those rows now having names, we can easily position our elements. Both the images and the container for the number go into the first row, and the text will go to the second row. So in the example above, we add the grid-area to the CSS for the class we applied to the div in the HTML. With those few lines, we have defined the layout.

To achieve the overlay effect for the number, the white box will be in its container and gets a fixed width and height. We can then use flex to center it in the container.

But how do we get from this to the desktop version, you may ask? Pretty easily, actually! For the overall design of the website, we are already using a 14-column grid on the desktop for all elements. If we overlay the design with some grid markers, we see the widths everything should take approximately.

Obviously, our named areas from the mobile view will not really help us for this version, but we can simply update them in a media query for our desktop view and also define different area names:

.container {  display: grid;
  grid-template-columns: repeat(14, minmax(0, 1fr));
  grid-template-rows: repeat(2, 1fr);
  gap: 1.2rem;
  grid-auto-flow: row;
  grid-template-areas:
    "images images images images images . numbering numbering numbering single-image single-image single-image single-image single-image"
    "images images images images images . text text text single-image single-image single-image single-image single-image";
}

.images { grid-area: images; }

.numbering { grid-area: numbering; }

.text { grid-area: text; }

.single-image { grid-area: single-image; }

Let me be the first one to say that, yes, this is really not a pretty way of defining this, but unfortunately, the template-areas syntax does not include the repeat keyword as the column definition does.

But take a moment and have a closer look. What you can see is that we define the first five columns to belong to the images name in both rows, then we have a period, which means nothing goes here, then we have three columns for the numbering in row one and three for the text in row two, and at the end, five columns for single-image. Personally, I like to use an online generator that allows me to visually define these areas and copy the needed CSS.

Now with just under 20 lines of code, we have completely changed the layout without having touched the very simple HTML structure at all! But what about the alternative version for 2 and 4? They only use a slightly different layout, so why not add some classes for .version-a and .version-b on the container and have the grid-template-areas defined by that on the desktop? It is that simple. Look at the following:

  .version-1 {
      grid-template-areas:
    "images images images images images . numbering numbering numbering single-image single-image single-image single-image single-image"
    "images images images images images . text text text single-image single-image single-image single-image single-image";
  }
.version-1 .single-image {
  grid-area: single-image;
  display:block;
 }
.version-2 { grid-template-areas: ". numbering numbering numbering . . images images images images images images images images" ". text text text . . images images images images images images images images"; }

To me, this is still pretty crazy, to be honest. For the longest time, a layout like this would have been completely out of reach or very complicated to make and having shared HTML between versions 1 and 2 would have been near impossible, at least for the complete HTML. Now we can just wave a magic wand and update where it should show up. Pretty heady stuff.

Another practical example where this helped me a lot was defining areas for a product detail page on an e-commerce website. Being able to move elements around to where they make sense in different contexts is amazing, but it also means that you need to adjust your mental model a bit to how HTML and CSS are connected. And this is even just the beginning. With container queries and layers, there is much on the horizon that will open up a lot more possibilities in the future, and I am totally here for it!

Finally, here is the full version of the design with everything pulled together:

See the Pen Untitled [forked] by Pfenya.

Additionally, if you are curious about the final live webpage, it can be found here.

Quick Tip: How to Disable Text Selection Highlighting in CSS

Category Image 052

There are two main CSS properties that control text selection highlighting: user-select and -webkit-user-select. These properties are used to specify whether or not users are able to select text on the web page.

UNLIMITED DOWNLOADS: Email, admin, landing page & website templates

Starting at only $16.50 per month!

To disable text selection highlighting in CSS, you can set the value of the user-select property to none:

body {
   -webkit-user-select: none;  /* for Safari */
   -moz-user-select: none;     /* for Firefox */
   -ms-user-select: none;      /* for Internet Explorer */
   user-select: none;          /* for modern browsers */
}

In this example, the user-select property is applied to the body element, which means that text selection highlighting will be disabled for the entire page. If you want to disable text selection highlighting for a specific element, simply apply the property to that element instead of the body element.

It’s important to note that the -webkit-user-select and -moz-user-select properties are vendor-specific extensions, and are used to ensure compatibility with Safari and Firefox, respectively. The -ms-user-select property is used for compatibility with Internet Explorer. The standard user-select property should work in all modern browsers.

Create a Drop Down Menu with Search Box in CSS3 and HTML

Category Image 052

This post is originally published on Designmodo: Create a Drop Down Menu with Search Box in CSS3 and HTML

Create a Drop Down Menu with Search Box in CSS3 and HTML

Topic: CSS3 Difficulty: Intermediate Estimated Completion Time: 45 min In this tutorial, we will be creating a flat style navigation with a search box and dropdown menu from the Square UI. Slides: HTML Static Website Builder Search Bar with Dropdown …

For more information please contact Designmodo